jquery.bxslider.js 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628
  1. /**
  2. * bxSlider v4.2.5
  3. * Copyright 2013-2015 Steven Wanderski
  4. * Written while drinking Belgian ales and listening to jazz
  5. * Licensed under MIT (http://opensource.org/licenses/MIT)
  6. */
  7. /*
  8. Patched to fix issue #960
  9. See: https://github.com/stevenwanderski/bxslider-4/pull/1133/commits/c32dd309ef6801fd294c631a2ecb889084e713d5
  10. Patched to fix https://bitbucket.org/fastlinemedia/beaver-builder-plugin/issues/1292/bx-slider-bug-with-links-in-firefox-59
  11. Ref: https://github.com/stevenwanderski/bxslider-4/issues/1188
  12. */
  13. ;(function($) {
  14. var defaults = {
  15. // GENERAL
  16. mode: 'horizontal',
  17. slideSelector: '',
  18. infiniteLoop: true,
  19. hideControlOnEnd: false,
  20. speed: 500,
  21. easing: null,
  22. slideMargin: 0,
  23. startSlide: 0,
  24. randomStart: false,
  25. captions: false,
  26. ticker: false,
  27. tickerHover: false,
  28. adaptiveHeight: false,
  29. adaptiveHeightSpeed: 500,
  30. video: false,
  31. useCSS: true,
  32. preloadImages: 'visible',
  33. responsive: true,
  34. slideZIndex: 50,
  35. wrapperClass: 'bx-wrapper',
  36. // TOUCH
  37. touchEnabled: true,
  38. swipeThreshold: 50,
  39. oneToOneTouch: true,
  40. preventDefaultSwipeX: true,
  41. preventDefaultSwipeY: false,
  42. // ACCESSIBILITY
  43. ariaLive: true,
  44. ariaHidden: true,
  45. // KEYBOARD
  46. keyboardEnabled: false,
  47. // PAGER
  48. pager: true,
  49. pagerType: 'full',
  50. pagerShortSeparator: ' / ',
  51. pagerSelector: null,
  52. buildPager: null,
  53. pagerCustom: null,
  54. // CONTROLS
  55. controls: true,
  56. nextText: 'Next',
  57. prevText: 'Prev',
  58. nextSelector: null,
  59. prevSelector: null,
  60. autoControls: false,
  61. startText: 'Start',
  62. stopText: 'Stop',
  63. autoControlsCombine: false,
  64. autoControlsSelector: null,
  65. // AUTO
  66. auto: false,
  67. pause: 4000,
  68. autoStart: true,
  69. autoDirection: 'next',
  70. stopAutoOnClick: false,
  71. autoHover: false,
  72. autoDelay: 0,
  73. autoSlideForOnePage: false,
  74. // CAROUSEL
  75. minSlides: 1,
  76. maxSlides: 1,
  77. moveSlides: 0,
  78. slideWidth: 0,
  79. shrinkItems: false,
  80. // CALLBACKS
  81. onSliderLoad: function() { return true; },
  82. onSlideBefore: function() { return true; },
  83. onSlideAfter: function() { return true; },
  84. onSlideNext: function() { return true; },
  85. onSlidePrev: function() { return true; },
  86. onSliderResize: function() { return true; }
  87. };
  88. $.fn.bxSlider = function(options) {
  89. if (this.length === 0) {
  90. return this;
  91. }
  92. // support multiple elements
  93. if (this.length > 1) {
  94. this.each(function() {
  95. $(this).bxSlider(options);
  96. });
  97. return this;
  98. }
  99. // create a namespace to be used throughout the plugin
  100. var slider = {},
  101. // set a reference to our slider element
  102. el = this,
  103. // get the original window dimens (thanks a lot IE)
  104. windowWidth = $(window).width(),
  105. windowHeight = $(window).height();
  106. // Return if slider is already initialized
  107. if ($(el).data('bxSlider')) { return; }
  108. /**
  109. * ===================================================================================
  110. * = PRIVATE FUNCTIONS
  111. * ===================================================================================
  112. */
  113. /**
  114. * Initializes namespace settings to be used throughout plugin
  115. */
  116. var init = function() {
  117. // Return if slider is already initialized
  118. if ($(el).data('bxSlider')) { return; }
  119. // merge user-supplied options with the defaults
  120. slider.settings = $.extend({}, defaults, options);
  121. // parse slideWidth setting
  122. slider.settings.slideWidth = parseInt(slider.settings.slideWidth);
  123. // store the original children
  124. slider.children = el.children(slider.settings.slideSelector);
  125. // check if actual number of slides is less than minSlides / maxSlides
  126. if (slider.children.length < slider.settings.minSlides) { slider.settings.minSlides = slider.children.length; }
  127. if (slider.children.length < slider.settings.maxSlides) { slider.settings.maxSlides = slider.children.length; }
  128. // if random start, set the startSlide setting to random number
  129. if (slider.settings.randomStart) { slider.settings.startSlide = Math.floor(Math.random() * slider.children.length); }
  130. // store active slide information
  131. slider.active = { index: slider.settings.startSlide };
  132. // store if the slider is in carousel mode (displaying / moving multiple slides)
  133. slider.carousel = slider.settings.minSlides > 1 || slider.settings.maxSlides > 1 ? true : false;
  134. // if carousel, force preloadImages = 'all'
  135. if (slider.carousel) { slider.settings.preloadImages = 'all'; }
  136. // calculate the min / max width thresholds based on min / max number of slides
  137. // used to setup and update carousel slides dimensions
  138. slider.minThreshold = (slider.settings.minSlides * slider.settings.slideWidth) + ((slider.settings.minSlides - 1) * slider.settings.slideMargin);
  139. slider.maxThreshold = (slider.settings.maxSlides * slider.settings.slideWidth) + ((slider.settings.maxSlides - 1) * slider.settings.slideMargin);
  140. // store the current state of the slider (if currently animating, working is true)
  141. slider.working = false;
  142. // initialize the controls object
  143. slider.controls = {};
  144. // initialize an auto interval
  145. slider.interval = null;
  146. // determine which property to use for transitions
  147. slider.animProp = slider.settings.mode === 'vertical' ? 'top' : 'left';
  148. // determine if hardware acceleration can be used
  149. slider.usingCSS = slider.settings.useCSS && slider.settings.mode !== 'fade' && (function() {
  150. // create our test div element
  151. var div = document.createElement('div'),
  152. // css transition properties
  153. props = ['WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective'];
  154. // test for each property
  155. for (var i = 0; i < props.length; i++) {
  156. if (div.style[props[i]] !== undefined) {
  157. slider.cssPrefix = props[i].replace('Perspective', '').toLowerCase();
  158. slider.animProp = '-' + slider.cssPrefix + '-transform';
  159. return true;
  160. }
  161. }
  162. return false;
  163. }());
  164. // if vertical mode always make maxSlides and minSlides equal
  165. if (slider.settings.mode === 'vertical') { slider.settings.maxSlides = slider.settings.minSlides; }
  166. // save original style data
  167. el.data('origStyle', el.attr('style'));
  168. el.children(slider.settings.slideSelector).each(function() {
  169. $(this).data('origStyle', $(this).attr('style'));
  170. });
  171. // perform all DOM / CSS modifications
  172. setup();
  173. };
  174. /**
  175. * Performs all DOM and CSS modifications
  176. */
  177. var setup = function() {
  178. var preloadSelector = slider.children.eq(slider.settings.startSlide); // set the default preload selector (visible)
  179. // wrap el in a wrapper
  180. el.wrap('<div class="' + slider.settings.wrapperClass + '"><div class="bx-viewport"></div></div>');
  181. // store a namespace reference to .bx-viewport
  182. slider.viewport = el.parent();
  183. // add aria-live if the setting is enabled and ticker mode is disabled
  184. if (slider.settings.ariaLive && !slider.settings.ticker) {
  185. slider.viewport.attr('aria-live', 'polite');
  186. }
  187. // add a loading div to display while images are loading
  188. slider.loader = $('<div class="bx-loading" />');
  189. slider.viewport.prepend(slider.loader);
  190. // set el to a massive width, to hold any needed slides
  191. // also strip any margin and padding from el
  192. el.css({
  193. width: slider.settings.mode === 'horizontal' ? (slider.children.length * 1000 + 215) + '%' : 'auto',
  194. position: 'relative'
  195. });
  196. // if using CSS, add the easing property
  197. if (slider.usingCSS && slider.settings.easing) {
  198. el.css('-' + slider.cssPrefix + '-transition-timing-function', slider.settings.easing);
  199. // if not using CSS and no easing value was supplied, use the default JS animation easing (swing)
  200. } else if (!slider.settings.easing) {
  201. slider.settings.easing = 'swing';
  202. }
  203. // make modifications to the viewport (.bx-viewport)
  204. slider.viewport.css({
  205. width: '100%',
  206. overflow: 'hidden',
  207. position: 'relative'
  208. });
  209. slider.viewport.parent().css({
  210. maxWidth: getViewportMaxWidth()
  211. });
  212. // make modification to the wrapper (.bx-wrapper)
  213. if (!slider.settings.pager && !slider.settings.controls) {
  214. slider.viewport.parent().css({
  215. margin: '0 auto 0px'
  216. });
  217. }
  218. // apply css to all slider children
  219. slider.children.css({
  220. float: slider.settings.mode === 'horizontal' ? 'left' : 'none',
  221. listStyle: 'none',
  222. position: 'relative'
  223. });
  224. // apply the calculated width after the float is applied to prevent scrollbar interference
  225. slider.children.css('width', getSlideWidth());
  226. // if slideMargin is supplied, add the css
  227. if (slider.settings.mode === 'horizontal' && slider.settings.slideMargin > 0) { slider.children.css('marginRight', slider.settings.slideMargin); }
  228. if (slider.settings.mode === 'vertical' && slider.settings.slideMargin > 0) { slider.children.css('marginBottom', slider.settings.slideMargin); }
  229. // if "fade" mode, add positioning and z-index CSS
  230. if (slider.settings.mode === 'fade') {
  231. slider.children.css({
  232. position: 'absolute',
  233. zIndex: 0,
  234. display: 'none'
  235. });
  236. // prepare the z-index on the showing element
  237. slider.children.eq(slider.settings.startSlide).css({zIndex: slider.settings.slideZIndex, display: 'block'});
  238. }
  239. // create an element to contain all slider controls (pager, start / stop, etc)
  240. slider.controls.el = $('<div class="bx-controls" />');
  241. // if captions are requested, add them
  242. if (slider.settings.captions) { appendCaptions(); }
  243. // check if startSlide is last slide
  244. slider.active.last = slider.settings.startSlide === getPagerQty() - 1;
  245. // if video is true, set up the fitVids plugin
  246. if (slider.settings.video) { el.fitVids(); }
  247. if (slider.settings.preloadImages === 'all' || slider.settings.ticker) { preloadSelector = slider.children; }
  248. // only check for control addition if not in "ticker" mode
  249. if (!slider.settings.ticker) {
  250. // if controls are requested, add them
  251. if (slider.settings.controls) { appendControls(); }
  252. // if auto is true, and auto controls are requested, add them
  253. if (slider.settings.auto && slider.settings.autoControls) { appendControlsAuto(); }
  254. // if pager is requested, add it
  255. if (slider.settings.pager) { appendPager(); }
  256. // if any control option is requested, add the controls wrapper
  257. if (slider.settings.controls || slider.settings.autoControls || slider.settings.pager) { slider.viewport.after(slider.controls.el); }
  258. // if ticker mode, do not allow a pager
  259. } else {
  260. slider.settings.pager = false;
  261. }
  262. loadElements(preloadSelector, start);
  263. };
  264. var loadElements = function(selector, callback) {
  265. var total = selector.find('img:not([src=""]), iframe').length,
  266. count = 0;
  267. if (total === 0) {
  268. callback();
  269. return;
  270. }
  271. selector.find('img:not([src=""]), iframe').each(function() {
  272. $(this).one('load error', function() {
  273. if (++count === total) { callback(); }
  274. }).each(function() {
  275. if (this.complete) { $(this).load(); }
  276. });
  277. });
  278. };
  279. /**
  280. * Start the slider
  281. */
  282. var start = function() {
  283. // if infinite loop, prepare additional slides
  284. if (slider.settings.infiniteLoop && slider.settings.mode !== 'fade' && !slider.settings.ticker) {
  285. var slice = slider.settings.mode === 'vertical' ? slider.settings.minSlides : slider.settings.maxSlides,
  286. sliceAppend = slider.children.slice(0, slice).clone(true).addClass('bx-clone'),
  287. slicePrepend = slider.children.slice(-slice).clone(true).addClass('bx-clone');
  288. if (slider.settings.ariaHidden) {
  289. sliceAppend.attr('aria-hidden', true);
  290. slicePrepend.attr('aria-hidden', true);
  291. }
  292. el.append(sliceAppend).prepend(slicePrepend);
  293. }
  294. // remove the loading DOM element
  295. slider.loader.remove();
  296. // set the left / top position of "el"
  297. setSlidePosition();
  298. // if "vertical" mode, always use adaptiveHeight to prevent odd behavior
  299. if (slider.settings.mode === 'vertical') { slider.settings.adaptiveHeight = true; }
  300. // set the viewport height
  301. slider.viewport.height(getViewportHeight());
  302. // make sure everything is positioned just right (same as a window resize)
  303. el.redrawSlider();
  304. // onSliderLoad callback
  305. slider.settings.onSliderLoad.call(el, slider.active.index);
  306. // slider has been fully initialized
  307. slider.initialized = true;
  308. // bind the resize call to the window
  309. if (slider.settings.responsive) { $(window).bind('resize', resizeWindow); }
  310. // if auto is true and has more than 1 page, start the show
  311. if (slider.settings.auto && slider.settings.autoStart && (getPagerQty() > 1 || slider.settings.autoSlideForOnePage)) { initAuto(); }
  312. // if ticker is true, start the ticker
  313. if (slider.settings.ticker) { initTicker(); }
  314. // if pager is requested, make the appropriate pager link active
  315. if (slider.settings.pager) { updatePagerActive(slider.settings.startSlide); }
  316. // check for any updates to the controls (like hideControlOnEnd updates)
  317. if (slider.settings.controls) { updateDirectionControls(); }
  318. // if touchEnabled is true, setup the touch events
  319. if (slider.settings.touchEnabled && !slider.settings.ticker) { initTouch(); }
  320. // if keyboardEnabled is true, setup the keyboard events
  321. if (slider.settings.keyboardEnabled && !slider.settings.ticker) {
  322. $(document).keydown(keyPress);
  323. }
  324. };
  325. /**
  326. * Returns the calculated height of the viewport, used to determine either adaptiveHeight or the maxHeight value
  327. */
  328. var getViewportHeight = function() {
  329. var height = 0;
  330. // first determine which children (slides) should be used in our height calculation
  331. var children = $();
  332. // if mode is not "vertical" and adaptiveHeight is false, include all children
  333. if (slider.settings.mode !== 'vertical' && !slider.settings.adaptiveHeight) {
  334. children = slider.children;
  335. } else {
  336. // if not carousel, return the single active child
  337. if (!slider.carousel) {
  338. children = slider.children.eq(slider.active.index);
  339. // if carousel, return a slice of children
  340. } else {
  341. // get the individual slide index
  342. var currentIndex = slider.settings.moveSlides === 1 ? slider.active.index : slider.active.index * getMoveBy();
  343. // add the current slide to the children
  344. children = slider.children.eq(currentIndex);
  345. // cycle through the remaining "showing" slides
  346. for (i = 1; i <= slider.settings.maxSlides - 1; i++) {
  347. // if looped back to the start
  348. if (currentIndex + i >= slider.children.length) {
  349. children = children.add(slider.children.eq(i - 1));
  350. } else {
  351. children = children.add(slider.children.eq(currentIndex + i));
  352. }
  353. }
  354. }
  355. }
  356. // if "vertical" mode, calculate the sum of the heights of the children
  357. if (slider.settings.mode === 'vertical') {
  358. children.each(function(index) {
  359. height += $(this).outerHeight();
  360. });
  361. // add user-supplied margins
  362. if (slider.settings.slideMargin > 0) {
  363. height += slider.settings.slideMargin * (slider.settings.minSlides - 1);
  364. }
  365. // if not "vertical" mode, calculate the max height of the children
  366. } else {
  367. height = Math.max.apply(Math, children.map(function() {
  368. return $(this).outerHeight(false);
  369. }).get());
  370. }
  371. if (slider.viewport.css('box-sizing') === 'border-box') {
  372. height += parseFloat(slider.viewport.css('padding-top')) + parseFloat(slider.viewport.css('padding-bottom')) +
  373. parseFloat(slider.viewport.css('border-top-width')) + parseFloat(slider.viewport.css('border-bottom-width'));
  374. } else if (slider.viewport.css('box-sizing') === 'padding-box') {
  375. height += parseFloat(slider.viewport.css('padding-top')) + parseFloat(slider.viewport.css('padding-bottom'));
  376. }
  377. return height;
  378. };
  379. /**
  380. * Returns the calculated width to be used for the outer wrapper / viewport
  381. */
  382. var getViewportMaxWidth = function() {
  383. var width = '100%';
  384. if (slider.settings.slideWidth > 0) {
  385. if (slider.settings.mode === 'horizontal') {
  386. width = (slider.settings.maxSlides * slider.settings.slideWidth) + ((slider.settings.maxSlides - 1) * slider.settings.slideMargin);
  387. } else {
  388. width = slider.settings.slideWidth;
  389. }
  390. }
  391. return width;
  392. };
  393. /**
  394. * Returns the calculated width to be applied to each slide
  395. */
  396. var getSlideWidth = function() {
  397. var newElWidth = slider.settings.slideWidth, // start with any user-supplied slide width
  398. wrapWidth = slider.viewport.width(); // get the current viewport width
  399. // if slide width was not supplied, or is larger than the viewport use the viewport width
  400. if (slider.settings.slideWidth === 0 ||
  401. (slider.settings.slideWidth > wrapWidth && !slider.carousel) ||
  402. slider.settings.mode === 'vertical') {
  403. newElWidth = wrapWidth;
  404. // if carousel, use the thresholds to determine the width
  405. } else if (slider.settings.maxSlides > 1 && slider.settings.mode === 'horizontal') {
  406. if (wrapWidth > slider.maxThreshold) {
  407. return newElWidth;
  408. } else if (wrapWidth < slider.minThreshold) {
  409. newElWidth = (wrapWidth - (slider.settings.slideMargin * (slider.settings.minSlides - 1))) / slider.settings.minSlides;
  410. } else if (slider.settings.shrinkItems) {
  411. newElWidth = Math.floor((wrapWidth + slider.settings.slideMargin) / (Math.ceil((wrapWidth + slider.settings.slideMargin) / (newElWidth + slider.settings.slideMargin))) - slider.settings.slideMargin);
  412. }
  413. }
  414. return newElWidth;
  415. };
  416. /**
  417. * Returns the number of slides currently visible in the viewport (includes partially visible slides)
  418. */
  419. var getNumberSlidesShowing = function() {
  420. var slidesShowing = 1,
  421. childWidth = null;
  422. if (slider.settings.mode === 'horizontal' && slider.settings.slideWidth > 0) {
  423. // if viewport is smaller than minThreshold, return minSlides
  424. if (slider.viewport.width() < slider.minThreshold) {
  425. slidesShowing = slider.settings.minSlides;
  426. // if viewport is larger than maxThreshold, return maxSlides
  427. } else if (slider.viewport.width() > slider.maxThreshold) {
  428. slidesShowing = slider.settings.maxSlides;
  429. // if viewport is between min / max thresholds, divide viewport width by first child width
  430. } else {
  431. childWidth = slider.children.first().width() + slider.settings.slideMargin;
  432. slidesShowing = Math.floor((slider.viewport.width() +
  433. slider.settings.slideMargin) / childWidth);
  434. }
  435. // if "vertical" mode, slides showing will always be minSlides
  436. } else if (slider.settings.mode === 'vertical') {
  437. slidesShowing = slider.settings.minSlides;
  438. }
  439. return slidesShowing;
  440. };
  441. /**
  442. * Returns the number of pages (one full viewport of slides is one "page")
  443. */
  444. var getPagerQty = function() {
  445. var pagerQty = 0,
  446. breakPoint = 0,
  447. counter = 0;
  448. // if moveSlides is specified by the user
  449. if (slider.settings.moveSlides > 0) {
  450. if (slider.settings.infiniteLoop) {
  451. pagerQty = Math.ceil(slider.children.length / getMoveBy());
  452. } else {
  453. // when breakpoint goes above children length, counter is the number of pages
  454. while (breakPoint < slider.children.length) {
  455. ++pagerQty;
  456. breakPoint = counter + getNumberSlidesShowing();
  457. counter += slider.settings.moveSlides <= getNumberSlidesShowing() ? slider.settings.moveSlides : getNumberSlidesShowing();
  458. }
  459. }
  460. // if moveSlides is 0 (auto) divide children length by sides showing, then round up
  461. } else {
  462. pagerQty = Math.ceil(slider.children.length / getNumberSlidesShowing());
  463. }
  464. return pagerQty;
  465. };
  466. /**
  467. * Returns the number of individual slides by which to shift the slider
  468. */
  469. var getMoveBy = function() {
  470. // if moveSlides was set by the user and moveSlides is less than number of slides showing
  471. if (slider.settings.moveSlides > 0 && slider.settings.moveSlides <= getNumberSlidesShowing()) {
  472. return slider.settings.moveSlides;
  473. }
  474. // if moveSlides is 0 (auto)
  475. return getNumberSlidesShowing();
  476. };
  477. /**
  478. * Sets the slider's (el) left or top position
  479. */
  480. var setSlidePosition = function() {
  481. var position, lastChild, lastShowingIndex;
  482. // if last slide, not infinite loop, and number of children is larger than specified maxSlides
  483. if (slider.children.length > slider.settings.maxSlides && slider.active.last && !slider.settings.infiniteLoop) {
  484. if (slider.settings.mode === 'horizontal') {
  485. // get the last child's position
  486. lastChild = slider.children.last();
  487. position = lastChild.position();
  488. // set the left position
  489. setPositionProperty(-(position.left - (slider.viewport.width() - lastChild.outerWidth())), 'reset', 0);
  490. } else if (slider.settings.mode === 'vertical') {
  491. // get the last showing index's position
  492. lastShowingIndex = slider.children.length - slider.settings.minSlides;
  493. position = slider.children.eq(lastShowingIndex).position();
  494. // set the top position
  495. setPositionProperty(-position.top, 'reset', 0);
  496. }
  497. // if not last slide
  498. } else {
  499. // get the position of the first showing slide
  500. position = slider.children.eq(slider.active.index * getMoveBy()).position();
  501. // check for last slide
  502. if (slider.active.index === getPagerQty() - 1) { slider.active.last = true; }
  503. // set the respective position
  504. if (position !== undefined) {
  505. if (slider.settings.mode === 'horizontal') { setPositionProperty(-position.left, 'reset', 0); }
  506. else if (slider.settings.mode === 'vertical') { setPositionProperty(-position.top, 'reset', 0); }
  507. }
  508. }
  509. };
  510. /**
  511. * Sets the el's animating property position (which in turn will sometimes animate el).
  512. * If using CSS, sets the transform property. If not using CSS, sets the top / left property.
  513. *
  514. * @param value (int)
  515. * - the animating property's value
  516. *
  517. * @param type (string) 'slide', 'reset', 'ticker'
  518. * - the type of instance for which the function is being
  519. *
  520. * @param duration (int)
  521. * - the amount of time (in ms) the transition should occupy
  522. *
  523. * @param params (array) optional
  524. * - an optional parameter containing any variables that need to be passed in
  525. */
  526. var setPositionProperty = function(value, type, duration, params) {
  527. var animateObj, propValue;
  528. // use CSS transform
  529. if (slider.usingCSS) {
  530. // determine the translate3d value
  531. propValue = slider.settings.mode === 'vertical' ? 'translate3d(0, ' + value + 'px, 0)' : 'translate3d(' + value + 'px, 0, 0)';
  532. // add the CSS transition-duration
  533. el.css('-' + slider.cssPrefix + '-transition-duration', duration / 1000 + 's');
  534. if (type === 'slide') {
  535. // set the property value
  536. el.css(slider.animProp, propValue);
  537. if (duration !== 0) {
  538. // bind a callback method - executes when CSS transition completes
  539. el.bind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function(e) {
  540. //make sure it's the correct one
  541. if (!$(e.target).is(el)) { return; }
  542. // unbind the callback
  543. el.unbind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd');
  544. updateAfterSlideTransition();
  545. });
  546. } else { //duration = 0
  547. updateAfterSlideTransition();
  548. }
  549. } else if (type === 'reset') {
  550. el.css(slider.animProp, propValue);
  551. } else if (type === 'ticker') {
  552. // make the transition use 'linear'
  553. el.css('-' + slider.cssPrefix + '-transition-timing-function', 'linear');
  554. el.css(slider.animProp, propValue);
  555. if (duration !== 0) {
  556. el.bind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function(e) {
  557. //make sure it's the correct one
  558. if (!$(e.target).is(el)) { return; }
  559. // unbind the callback
  560. el.unbind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd');
  561. // reset the position
  562. setPositionProperty(params.resetValue, 'reset', 0);
  563. // start the loop again
  564. tickerLoop();
  565. });
  566. } else { //duration = 0
  567. setPositionProperty(params.resetValue, 'reset', 0);
  568. tickerLoop();
  569. }
  570. }
  571. // use JS animate
  572. } else {
  573. animateObj = {};
  574. animateObj[slider.animProp] = value;
  575. if (type === 'slide') {
  576. el.animate(animateObj, duration, slider.settings.easing, function() {
  577. updateAfterSlideTransition();
  578. });
  579. } else if (type === 'reset') {
  580. el.css(slider.animProp, value);
  581. } else if (type === 'ticker') {
  582. el.animate(animateObj, duration, 'linear', function() {
  583. setPositionProperty(params.resetValue, 'reset', 0);
  584. // run the recursive loop after animation
  585. tickerLoop();
  586. });
  587. }
  588. }
  589. };
  590. /**
  591. * Populates the pager with proper amount of pages
  592. */
  593. var populatePager = function() {
  594. var pagerHtml = '',
  595. linkContent = '',
  596. pagerQty = getPagerQty();
  597. // loop through each pager item
  598. for (var i = 0; i < pagerQty; i++) {
  599. linkContent = '';
  600. // if a buildPager function is supplied, use it to get pager link value, else use index + 1
  601. if (slider.settings.buildPager && $.isFunction(slider.settings.buildPager) || slider.settings.pagerCustom) {
  602. linkContent = slider.settings.buildPager(i);
  603. slider.pagerEl.addClass('bx-custom-pager');
  604. } else {
  605. linkContent = i + 1;
  606. slider.pagerEl.addClass('bx-default-pager');
  607. }
  608. // var linkContent = slider.settings.buildPager && $.isFunction(slider.settings.buildPager) ? slider.settings.buildPager(i) : i + 1;
  609. // add the markup to the string
  610. pagerHtml += '<div class="bx-pager-item"><a href="" data-slide-index="' + i + '" class="bx-pager-link">' + linkContent + '</a></div>';
  611. }
  612. // populate the pager element with pager links
  613. slider.pagerEl.html(pagerHtml);
  614. };
  615. /**
  616. * Appends the pager to the controls element
  617. */
  618. var appendPager = function() {
  619. if (!slider.settings.pagerCustom) {
  620. // create the pager DOM element
  621. slider.pagerEl = $('<div class="bx-pager" />');
  622. // if a pager selector was supplied, populate it with the pager
  623. if (slider.settings.pagerSelector) {
  624. $(slider.settings.pagerSelector).html(slider.pagerEl);
  625. // if no pager selector was supplied, add it after the wrapper
  626. } else {
  627. slider.controls.el.addClass('bx-has-pager').append(slider.pagerEl);
  628. }
  629. // populate the pager
  630. populatePager();
  631. } else {
  632. slider.pagerEl = $(slider.settings.pagerCustom);
  633. }
  634. // assign the pager click binding
  635. slider.pagerEl.on('click touchend', 'a', clickPagerBind);
  636. };
  637. /**
  638. * Appends prev / next controls to the controls element
  639. */
  640. var appendControls = function() {
  641. slider.controls.next = $('<a class="bx-next" href="">' + slider.settings.nextText + '</a>');
  642. slider.controls.prev = $('<a class="bx-prev" href="">' + slider.settings.prevText + '</a>');
  643. // bind click actions to the controls
  644. slider.controls.next.bind('click touchend', clickNextBind);
  645. slider.controls.prev.bind('click touchend', clickPrevBind);
  646. // if nextSelector was supplied, populate it
  647. if (slider.settings.nextSelector) {
  648. $(slider.settings.nextSelector).append(slider.controls.next);
  649. }
  650. // if prevSelector was supplied, populate it
  651. if (slider.settings.prevSelector) {
  652. $(slider.settings.prevSelector).append(slider.controls.prev);
  653. }
  654. // if no custom selectors were supplied
  655. if (!slider.settings.nextSelector && !slider.settings.prevSelector) {
  656. // add the controls to the DOM
  657. slider.controls.directionEl = $('<div class="bx-controls-direction" />');
  658. // add the control elements to the directionEl
  659. slider.controls.directionEl.append(slider.controls.prev).append(slider.controls.next);
  660. // slider.viewport.append(slider.controls.directionEl);
  661. slider.controls.el.addClass('bx-has-controls-direction').append(slider.controls.directionEl);
  662. }
  663. };
  664. /**
  665. * Appends start / stop auto controls to the controls element
  666. */
  667. var appendControlsAuto = function() {
  668. slider.controls.start = $('<div class="bx-controls-auto-item"><a class="bx-start" href="">' + slider.settings.startText + '</a></div>');
  669. slider.controls.stop = $('<div class="bx-controls-auto-item"><a class="bx-stop" href="">' + slider.settings.stopText + '</a></div>');
  670. // add the controls to the DOM
  671. slider.controls.autoEl = $('<div class="bx-controls-auto" />');
  672. // bind click actions to the controls
  673. slider.controls.autoEl.on('click', '.bx-start', clickStartBind);
  674. slider.controls.autoEl.on('click', '.bx-stop', clickStopBind);
  675. // if autoControlsCombine, insert only the "start" control
  676. if (slider.settings.autoControlsCombine) {
  677. slider.controls.autoEl.append(slider.controls.start);
  678. // if autoControlsCombine is false, insert both controls
  679. } else {
  680. slider.controls.autoEl.append(slider.controls.start).append(slider.controls.stop);
  681. }
  682. // if auto controls selector was supplied, populate it with the controls
  683. if (slider.settings.autoControlsSelector) {
  684. $(slider.settings.autoControlsSelector).html(slider.controls.autoEl);
  685. // if auto controls selector was not supplied, add it after the wrapper
  686. } else {
  687. slider.controls.el.addClass('bx-has-controls-auto').append(slider.controls.autoEl);
  688. }
  689. // update the auto controls
  690. updateAutoControls(slider.settings.autoStart ? 'stop' : 'start');
  691. };
  692. /**
  693. * Appends image captions to the DOM
  694. */
  695. var appendCaptions = function() {
  696. // cycle through each child
  697. slider.children.each(function(index) {
  698. // get the image title attribute
  699. var title = $(this).find('img:first').attr('title');
  700. // append the caption
  701. if (title !== undefined && ('' + title).length) {
  702. $(this).append('<div class="bx-caption"><span>' + title + '</span></div>');
  703. }
  704. });
  705. };
  706. /**
  707. * Click next binding
  708. *
  709. * @param e (event)
  710. * - DOM event object
  711. */
  712. var clickNextBind = function(e) {
  713. e.preventDefault();
  714. if (slider.controls.el.hasClass('disabled')) { return; }
  715. // if auto show is running, stop it
  716. if (slider.settings.auto && slider.settings.stopAutoOnClick) { el.stopAuto(); }
  717. el.goToNextSlide();
  718. };
  719. /**
  720. * Click prev binding
  721. *
  722. * @param e (event)
  723. * - DOM event object
  724. */
  725. var clickPrevBind = function(e) {
  726. e.preventDefault();
  727. if (slider.controls.el.hasClass('disabled')) { return; }
  728. // if auto show is running, stop it
  729. if (slider.settings.auto && slider.settings.stopAutoOnClick) { el.stopAuto(); }
  730. el.goToPrevSlide();
  731. };
  732. /**
  733. * Click start binding
  734. *
  735. * @param e (event)
  736. * - DOM event object
  737. */
  738. var clickStartBind = function(e) {
  739. el.startAuto();
  740. e.preventDefault();
  741. };
  742. /**
  743. * Click stop binding
  744. *
  745. * @param e (event)
  746. * - DOM event object
  747. */
  748. var clickStopBind = function(e) {
  749. el.stopAuto();
  750. e.preventDefault();
  751. };
  752. /**
  753. * Click pager binding
  754. *
  755. * @param e (event)
  756. * - DOM event object
  757. */
  758. var clickPagerBind = function(e) {
  759. var pagerLink, pagerIndex;
  760. e.preventDefault();
  761. if (slider.controls.el.hasClass('disabled')) {
  762. return;
  763. }
  764. // if auto show is running, stop it
  765. if (slider.settings.auto && slider.settings.stopAutoOnClick) { el.stopAuto(); }
  766. pagerLink = $(e.currentTarget);
  767. if (pagerLink.attr('data-slide-index') !== undefined) {
  768. pagerIndex = parseInt(pagerLink.attr('data-slide-index'));
  769. // if clicked pager link is not active, continue with the goToSlide call
  770. if (pagerIndex !== slider.active.index) { el.goToSlide(pagerIndex); }
  771. }
  772. };
  773. /**
  774. * Updates the pager links with an active class
  775. *
  776. * @param slideIndex (int)
  777. * - index of slide to make active
  778. */
  779. var updatePagerActive = function(slideIndex) {
  780. // if "short" pager type
  781. var len = slider.children.length; // nb of children
  782. if (slider.settings.pagerType === 'short') {
  783. if (slider.settings.maxSlides > 1) {
  784. len = Math.ceil(slider.children.length / slider.settings.maxSlides);
  785. }
  786. slider.pagerEl.html((slideIndex + 1) + slider.settings.pagerShortSeparator + len);
  787. return;
  788. }
  789. // remove all pager active classes
  790. slider.pagerEl.find('a').removeClass('active');
  791. // apply the active class for all pagers
  792. slider.pagerEl.each(function(i, el) { $(el).find('a').eq(slideIndex).addClass('active'); });
  793. };
  794. /**
  795. * Performs needed actions after a slide transition
  796. */
  797. var updateAfterSlideTransition = function() {
  798. // if infinite loop is true
  799. if (slider.settings.infiniteLoop) {
  800. var position = '';
  801. // first slide
  802. if (slider.active.index === 0) {
  803. // set the new position
  804. position = slider.children.eq(0).position();
  805. // carousel, last slide
  806. } else if (slider.active.index === getPagerQty() - 1 && slider.carousel) {
  807. position = slider.children.eq((getPagerQty() - 1) * getMoveBy()).position();
  808. // last slide
  809. } else if (slider.active.index === slider.children.length - 1) {
  810. position = slider.children.eq(slider.children.length - 1).position();
  811. }
  812. if (position) {
  813. if (slider.settings.mode === 'horizontal') { setPositionProperty(-position.left, 'reset', 0); }
  814. else if (slider.settings.mode === 'vertical') { setPositionProperty(-position.top, 'reset', 0); }
  815. }
  816. }
  817. // declare that the transition is complete
  818. slider.working = false;
  819. // onSlideAfter callback
  820. slider.settings.onSlideAfter.call(el, slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index);
  821. };
  822. /**
  823. * Updates the auto controls state (either active, or combined switch)
  824. *
  825. * @param state (string) "start", "stop"
  826. * - the new state of the auto show
  827. */
  828. var updateAutoControls = function(state) {
  829. // if autoControlsCombine is true, replace the current control with the new state
  830. if (slider.settings.autoControlsCombine) {
  831. slider.controls.autoEl.html(slider.controls[state]);
  832. // if autoControlsCombine is false, apply the "active" class to the appropriate control
  833. } else {
  834. slider.controls.autoEl.find('a').removeClass('active');
  835. slider.controls.autoEl.find('a:not(.bx-' + state + ')').addClass('active');
  836. }
  837. };
  838. /**
  839. * Updates the direction controls (checks if either should be hidden)
  840. */
  841. var updateDirectionControls = function() {
  842. if (getPagerQty() === 1) {
  843. slider.controls.prev.addClass('disabled');
  844. slider.controls.next.addClass('disabled');
  845. } else if (!slider.settings.infiniteLoop && slider.settings.hideControlOnEnd) {
  846. // if first slide
  847. if (slider.active.index === 0) {
  848. slider.controls.prev.addClass('disabled');
  849. slider.controls.next.removeClass('disabled');
  850. // if last slide
  851. } else if (slider.active.index === getPagerQty() - 1) {
  852. slider.controls.next.addClass('disabled');
  853. slider.controls.prev.removeClass('disabled');
  854. // if any slide in the middle
  855. } else {
  856. slider.controls.prev.removeClass('disabled');
  857. slider.controls.next.removeClass('disabled');
  858. }
  859. }
  860. };
  861. /**
  862. * Initializes the auto process
  863. */
  864. var initAuto = function() {
  865. // if autoDelay was supplied, launch the auto show using a setTimeout() call
  866. if (slider.settings.autoDelay > 0) {
  867. var timeout = setTimeout(el.startAuto, slider.settings.autoDelay);
  868. // if autoDelay was not supplied, start the auto show normally
  869. } else {
  870. el.startAuto();
  871. //add focus and blur events to ensure its running if timeout gets paused
  872. $(window).focus(function() {
  873. el.startAuto();
  874. }).blur(function() {
  875. el.stopAuto();
  876. });
  877. }
  878. // if autoHover is requested
  879. if (slider.settings.autoHover) {
  880. // on el hover
  881. el.hover(function() {
  882. // if the auto show is currently playing (has an active interval)
  883. if (slider.interval) {
  884. // stop the auto show and pass true argument which will prevent control update
  885. el.stopAuto(true);
  886. // create a new autoPaused value which will be used by the relative "mouseout" event
  887. slider.autoPaused = true;
  888. }
  889. }, function() {
  890. // if the autoPaused value was created be the prior "mouseover" event
  891. if (slider.autoPaused) {
  892. // start the auto show and pass true argument which will prevent control update
  893. el.startAuto(true);
  894. // reset the autoPaused value
  895. slider.autoPaused = null;
  896. }
  897. });
  898. }
  899. };
  900. /**
  901. * Initializes the ticker process
  902. */
  903. var initTicker = function() {
  904. var startPosition = 0,
  905. position, transform, value, idx, ratio, property, newSpeed, totalDimens;
  906. // if autoDirection is "next", append a clone of the entire slider
  907. if (slider.settings.autoDirection === 'next') {
  908. el.append(slider.children.clone().addClass('bx-clone'));
  909. // if autoDirection is "prev", prepend a clone of the entire slider, and set the left position
  910. } else {
  911. el.prepend(slider.children.clone().addClass('bx-clone'));
  912. position = slider.children.first().position();
  913. startPosition = slider.settings.mode === 'horizontal' ? -position.left : -position.top;
  914. }
  915. setPositionProperty(startPosition, 'reset', 0);
  916. // do not allow controls in ticker mode
  917. slider.settings.pager = false;
  918. slider.settings.controls = false;
  919. slider.settings.autoControls = false;
  920. // if autoHover is requested
  921. if (slider.settings.tickerHover) {
  922. if (slider.usingCSS) {
  923. idx = slider.settings.mode === 'horizontal' ? 4 : 5;
  924. slider.viewport.hover(function() {
  925. transform = el.css('-' + slider.cssPrefix + '-transform');
  926. value = parseFloat(transform.split(',')[idx]);
  927. setPositionProperty(value, 'reset', 0);
  928. }, function() {
  929. totalDimens = 0;
  930. slider.children.each(function(index) {
  931. totalDimens += slider.settings.mode === 'horizontal' ? $(this).outerWidth(true) : $(this).outerHeight(true);
  932. });
  933. // calculate the speed ratio (used to determine the new speed to finish the paused animation)
  934. ratio = slider.settings.speed / totalDimens;
  935. // determine which property to use
  936. property = slider.settings.mode === 'horizontal' ? 'left' : 'top';
  937. // calculate the new speed
  938. newSpeed = ratio * (totalDimens - (Math.abs(parseInt(value))));
  939. tickerLoop(newSpeed);
  940. });
  941. } else {
  942. // on el hover
  943. slider.viewport.hover(function() {
  944. el.stop();
  945. }, function() {
  946. // calculate the total width of children (used to calculate the speed ratio)
  947. totalDimens = 0;
  948. slider.children.each(function(index) {
  949. totalDimens += slider.settings.mode === 'horizontal' ? $(this).outerWidth(true) : $(this).outerHeight(true);
  950. });
  951. // calculate the speed ratio (used to determine the new speed to finish the paused animation)
  952. ratio = slider.settings.speed / totalDimens;
  953. // determine which property to use
  954. property = slider.settings.mode === 'horizontal' ? 'left' : 'top';
  955. // calculate the new speed
  956. newSpeed = ratio * (totalDimens - (Math.abs(parseInt(el.css(property)))));
  957. tickerLoop(newSpeed);
  958. });
  959. }
  960. }
  961. // start the ticker loop
  962. tickerLoop();
  963. };
  964. /**
  965. * Runs a continuous loop, news ticker-style
  966. */
  967. var tickerLoop = function(resumeSpeed) {
  968. var speed = resumeSpeed ? resumeSpeed : slider.settings.speed,
  969. position = {left: 0, top: 0},
  970. reset = {left: 0, top: 0},
  971. animateProperty, resetValue, params;
  972. // if "next" animate left position to last child, then reset left to 0
  973. if (slider.settings.autoDirection === 'next') {
  974. position = el.find('.bx-clone').first().position();
  975. // if "prev" animate left position to 0, then reset left to first non-clone child
  976. } else {
  977. reset = slider.children.first().position();
  978. }
  979. animateProperty = slider.settings.mode === 'horizontal' ? -position.left : -position.top;
  980. resetValue = slider.settings.mode === 'horizontal' ? -reset.left : -reset.top;
  981. params = {resetValue: resetValue};
  982. setPositionProperty(animateProperty, 'ticker', speed, params);
  983. };
  984. /**
  985. * Check if el is on screen
  986. */
  987. var isOnScreen = function(el) {
  988. var win = $(window),
  989. viewport = {
  990. top: win.scrollTop(),
  991. left: win.scrollLeft()
  992. },
  993. bounds = el.offset();
  994. viewport.right = viewport.left + win.width();
  995. viewport.bottom = viewport.top + win.height();
  996. bounds.right = bounds.left + el.outerWidth();
  997. bounds.bottom = bounds.top + el.outerHeight();
  998. return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
  999. };
  1000. /**
  1001. * Initializes keyboard events
  1002. */
  1003. var keyPress = function(e) {
  1004. var activeElementTag = document.activeElement.tagName.toLowerCase(),
  1005. tagFilters = 'input|textarea',
  1006. p = new RegExp(activeElementTag,['i']),
  1007. result = p.exec(tagFilters);
  1008. if (result == null && isOnScreen(el)) {
  1009. if (e.keyCode === 39) {
  1010. clickNextBind(e);
  1011. return false;
  1012. } else if (e.keyCode === 37) {
  1013. clickPrevBind(e);
  1014. return false;
  1015. }
  1016. }
  1017. };
  1018. /**
  1019. * Initializes touch events
  1020. */
  1021. var initTouch = function() {
  1022. // initialize object to contain all touch values
  1023. slider.touch = {
  1024. start: {x: 0, y: 0},
  1025. end: {x: 0, y: 0}
  1026. };
  1027. slider.viewport.bind('touchstart MSPointerDown pointerdown', onTouchStart);
  1028. //for browsers that have implemented pointer events and fire a click after
  1029. //every pointerup regardless of whether pointerup is on same screen location as pointerdown or not
  1030. slider.viewport.on('click', '.bxslider a', function(e) {
  1031. if (slider.viewport.hasClass('click-disabled')) {
  1032. e.preventDefault();
  1033. slider.viewport.removeClass('click-disabled');
  1034. }
  1035. });
  1036. };
  1037. /**
  1038. * Event handler for "touchstart"
  1039. *
  1040. * @param e (event)
  1041. * - DOM event object
  1042. */
  1043. var onTouchStart = function(e) {
  1044. //disable slider controls while user is interacting with slides to avoid slider freeze that happens on touch devices when a slide swipe happens immediately after interacting with slider controls
  1045. slider.controls.el.addClass('disabled');
  1046. if (slider.working) {
  1047. e.preventDefault();
  1048. slider.controls.el.removeClass('disabled');
  1049. } else {
  1050. // record the original position when touch starts
  1051. slider.touch.originalPos = el.position();
  1052. var orig = e.originalEvent,
  1053. touchPoints = (typeof orig.changedTouches !== 'undefined') ? orig.changedTouches : [orig];
  1054. // fix for https://github.com/stevenwanderski/bxslider-4/issues/1086
  1055. var chromePointerEvents = typeof PointerEvent === 'function';
  1056. if (chromePointerEvents && orig.pointerId === undefined) {
  1057. return;
  1058. }
  1059. // end fix
  1060. // record the starting touch x, y coordinates
  1061. slider.touch.start.x = touchPoints[0].pageX;
  1062. slider.touch.start.y = touchPoints[0].pageY;
  1063. if (slider.viewport.get(0).setPointerCapture) {
  1064. slider.pointerId = orig.pointerId;
  1065. if(slider.pointerId === 1) {
  1066. slider.viewport.get(0).setPointerCapture(slider.pointerId);
  1067. }
  1068. }
  1069. // bind a "touchmove" event to the viewport
  1070. slider.viewport.bind('touchmove MSPointerMove pointermove', onTouchMove);
  1071. // bind a "touchend" event to the viewport
  1072. slider.viewport.bind('touchend MSPointerUp pointerup', onTouchEnd);
  1073. slider.viewport.bind('MSPointerCancel pointercancel', onPointerCancel);
  1074. }
  1075. };
  1076. /**
  1077. * Cancel Pointer for Windows Phone
  1078. *
  1079. * @param e (event)
  1080. * - DOM event object
  1081. */
  1082. var onPointerCancel = function(e) {
  1083. /* onPointerCancel handler is needed to deal with situations when a touchend
  1084. doesn't fire after a touchstart (this happens on windows phones only) */
  1085. setPositionProperty(slider.touch.originalPos.left, 'reset', 0);
  1086. //remove handlers
  1087. slider.controls.el.removeClass('disabled');
  1088. slider.viewport.unbind('MSPointerCancel pointercancel', onPointerCancel);
  1089. slider.viewport.unbind('touchmove MSPointerMove pointermove', onTouchMove);
  1090. slider.viewport.unbind('touchend MSPointerUp pointerup', onTouchEnd);
  1091. if (slider.viewport.get(0).releasePointerCapture) {
  1092. slider.viewport.get(0).releasePointerCapture(slider.pointerId);
  1093. }
  1094. };
  1095. /**
  1096. * Event handler for "touchmove"
  1097. *
  1098. * @param e (event)
  1099. * - DOM event object
  1100. */
  1101. var onTouchMove = function(e) {
  1102. var orig = e.originalEvent,
  1103. touchPoints = (typeof orig.changedTouches !== 'undefined') ? orig.changedTouches : [orig],
  1104. // if scrolling on y axis, do not prevent default
  1105. xMovement = Math.abs(touchPoints[0].pageX - slider.touch.start.x),
  1106. yMovement = Math.abs(touchPoints[0].pageY - slider.touch.start.y),
  1107. value = 0,
  1108. change = 0;
  1109. // x axis swipe
  1110. if ((xMovement * 3) > yMovement && slider.settings.preventDefaultSwipeX) {
  1111. e.preventDefault();
  1112. // y axis swipe
  1113. } else if ((yMovement * 3) > xMovement && slider.settings.preventDefaultSwipeY) {
  1114. e.preventDefault();
  1115. }
  1116. if (slider.settings.mode !== 'fade' && slider.settings.oneToOneTouch) {
  1117. // if horizontal, drag along x axis
  1118. if (slider.settings.mode === 'horizontal') {
  1119. change = touchPoints[0].pageX - slider.touch.start.x;
  1120. value = slider.touch.originalPos.left + change;
  1121. // if vertical, drag along y axis
  1122. } else {
  1123. change = touchPoints[0].pageY - slider.touch.start.y;
  1124. value = slider.touch.originalPos.top + change;
  1125. }
  1126. setPositionProperty(value, 'reset', 0);
  1127. }
  1128. };
  1129. /**
  1130. * Event handler for "touchend"
  1131. *
  1132. * @param e (event)
  1133. * - DOM event object
  1134. */
  1135. var onTouchEnd = function(e) {
  1136. slider.viewport.unbind('touchmove MSPointerMove pointermove', onTouchMove);
  1137. //enable slider controls as soon as user stops interacing with slides
  1138. slider.controls.el.removeClass('disabled');
  1139. var orig = e.originalEvent,
  1140. touchPoints = (typeof orig.changedTouches !== 'undefined') ? orig.changedTouches : [orig],
  1141. value = 0,
  1142. distance = 0;
  1143. // record end x, y positions
  1144. slider.touch.end.x = touchPoints[0].pageX;
  1145. slider.touch.end.y = touchPoints[0].pageY;
  1146. // if fade mode, check if absolute x distance clears the threshold
  1147. if (slider.settings.mode === 'fade') {
  1148. distance = Math.abs(slider.touch.start.x - slider.touch.end.x);
  1149. if (distance >= slider.settings.swipeThreshold) {
  1150. if (slider.touch.start.x > slider.touch.end.x) {
  1151. el.goToNextSlide();
  1152. } else {
  1153. el.goToPrevSlide();
  1154. }
  1155. el.stopAuto();
  1156. }
  1157. // not fade mode
  1158. } else {
  1159. // calculate distance and el's animate property
  1160. if (slider.settings.mode === 'horizontal') {
  1161. distance = slider.touch.end.x - slider.touch.start.x;
  1162. value = slider.touch.originalPos.left;
  1163. } else {
  1164. distance = slider.touch.end.y - slider.touch.start.y;
  1165. value = slider.touch.originalPos.top;
  1166. }
  1167. // if not infinite loop and first / last slide, do not attempt a slide transition
  1168. if (!slider.settings.infiniteLoop && ((slider.active.index === 0 && distance > 0) || (slider.active.last && distance < 0))) {
  1169. setPositionProperty(value, 'reset', 200);
  1170. } else {
  1171. // check if distance clears threshold
  1172. if (Math.abs(distance) >= slider.settings.swipeThreshold) {
  1173. if (distance < 0) {
  1174. el.goToNextSlide();
  1175. } else {
  1176. el.goToPrevSlide();
  1177. }
  1178. el.stopAuto();
  1179. } else {
  1180. // el.animate(property, 200);
  1181. setPositionProperty(value, 'reset', 200);
  1182. }
  1183. }
  1184. }
  1185. slider.viewport.unbind('touchend MSPointerUp pointerup', onTouchEnd);
  1186. if (slider.viewport.get(0).releasePointerCapture) {
  1187. slider.viewport.get(0).releasePointerCapture(slider.pointerId);
  1188. }
  1189. };
  1190. /**
  1191. * Window resize event callback
  1192. */
  1193. var resizeWindow = function(e) {
  1194. // don't do anything if slider isn't initialized.
  1195. if (!slider.initialized) { return; }
  1196. // Delay if slider working.
  1197. if (slider.working) {
  1198. window.setTimeout(resizeWindow, 10);
  1199. } else {
  1200. // get the new window dimens (again, thank you IE)
  1201. var windowWidthNew = $(window).width(),
  1202. windowHeightNew = $(window).height();
  1203. // make sure that it is a true window resize
  1204. // *we must check this because our dinosaur friend IE fires a window resize event when certain DOM elements
  1205. // are resized. Can you just die already?*
  1206. if (windowWidth !== windowWidthNew || windowHeight !== windowHeightNew) {
  1207. // set the new window dimens
  1208. windowWidth = windowWidthNew;
  1209. windowHeight = windowHeightNew;
  1210. // update all dynamic elements
  1211. el.redrawSlider();
  1212. // Call user resize handler
  1213. slider.settings.onSliderResize.call(el, slider.active.index);
  1214. }
  1215. }
  1216. };
  1217. /**
  1218. * Adds an aria-hidden=true attribute to each element
  1219. *
  1220. * @param startVisibleIndex (int)
  1221. * - the first visible element's index
  1222. */
  1223. var applyAriaHiddenAttributes = function(startVisibleIndex) {
  1224. var numberOfSlidesShowing = getNumberSlidesShowing();
  1225. // only apply attributes if the setting is enabled and not in ticker mode
  1226. if (slider.settings.ariaHidden && !slider.settings.ticker) {
  1227. // add aria-hidden=true to all elements
  1228. slider.children.attr('aria-hidden', 'true');
  1229. // get the visible elements and change to aria-hidden=false
  1230. slider.children.slice(startVisibleIndex, startVisibleIndex + numberOfSlidesShowing).attr('aria-hidden', 'false');
  1231. }
  1232. };
  1233. /**
  1234. * Returns index according to present page range
  1235. *
  1236. * @param slideOndex (int)
  1237. * - the desired slide index
  1238. */
  1239. var setSlideIndex = function(slideIndex) {
  1240. if (slideIndex < 0) {
  1241. if (slider.settings.infiniteLoop) {
  1242. return getPagerQty() - 1;
  1243. }else {
  1244. //we don't go to undefined slides
  1245. return slider.active.index;
  1246. }
  1247. // if slideIndex is greater than children length, set active index to 0 (this happens during infinite loop)
  1248. } else if (slideIndex >= getPagerQty()) {
  1249. if (slider.settings.infiniteLoop) {
  1250. return 0;
  1251. } else {
  1252. //we don't move to undefined pages
  1253. return slider.active.index;
  1254. }
  1255. // set active index to requested slide
  1256. } else {
  1257. return slideIndex;
  1258. }
  1259. };
  1260. /**
  1261. * ===================================================================================
  1262. * = PUBLIC FUNCTIONS
  1263. * ===================================================================================
  1264. */
  1265. /**
  1266. * Performs slide transition to the specified slide
  1267. *
  1268. * @param slideIndex (int)
  1269. * - the destination slide's index (zero-based)
  1270. *
  1271. * @param direction (string)
  1272. * - INTERNAL USE ONLY - the direction of travel ("prev" / "next")
  1273. */
  1274. el.goToSlide = function(slideIndex, direction) {
  1275. // onSlideBefore, onSlideNext, onSlidePrev callbacks
  1276. // Allow transition canceling based on returned value
  1277. var performTransition = true,
  1278. moveBy = 0,
  1279. position = {left: 0, top: 0},
  1280. lastChild = null,
  1281. lastShowingIndex, eq, value, requestEl;
  1282. // store the old index
  1283. slider.oldIndex = slider.active.index;
  1284. //set new index
  1285. slider.active.index = setSlideIndex(slideIndex);
  1286. // if plugin is currently in motion, ignore request
  1287. if (slider.working || slider.active.index === slider.oldIndex) { return; }
  1288. // declare that plugin is in motion
  1289. slider.working = true;
  1290. performTransition = slider.settings.onSlideBefore.call(el, slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index);
  1291. // If transitions canceled, reset and return
  1292. if (typeof (performTransition) !== 'undefined' && !performTransition) {
  1293. slider.active.index = slider.oldIndex; // restore old index
  1294. slider.working = false; // is not in motion
  1295. return;
  1296. }
  1297. if (direction === 'next') {
  1298. // Prevent canceling in future functions or lack there-of from negating previous commands to cancel
  1299. if (!slider.settings.onSlideNext.call(el, slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index)) {
  1300. performTransition = false;
  1301. }
  1302. } else if (direction === 'prev') {
  1303. // Prevent canceling in future functions or lack there-of from negating previous commands to cancel
  1304. if (!slider.settings.onSlidePrev.call(el, slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index)) {
  1305. performTransition = false;
  1306. }
  1307. }
  1308. // check if last slide
  1309. slider.active.last = slider.active.index >= getPagerQty() - 1;
  1310. // update the pager with active class
  1311. if (slider.settings.pager || slider.settings.pagerCustom) { updatePagerActive(slider.active.index); }
  1312. // // check for direction control update
  1313. if (slider.settings.controls) { updateDirectionControls(); }
  1314. // if slider is set to mode: "fade"
  1315. if (slider.settings.mode === 'fade') {
  1316. // if adaptiveHeight is true and next height is different from current height, animate to the new height
  1317. if (slider.settings.adaptiveHeight && slider.viewport.height() !== getViewportHeight()) {
  1318. slider.viewport.animate({height: getViewportHeight()}, slider.settings.adaptiveHeightSpeed);
  1319. }
  1320. // fade out the visible child and reset its z-index value
  1321. slider.children.filter(':visible').fadeOut(slider.settings.speed).css({zIndex: 0});
  1322. // fade in the newly requested slide
  1323. slider.children.eq(slider.active.index).css('zIndex', slider.settings.slideZIndex + 1).fadeIn(slider.settings.speed, function() {
  1324. $(this).css('zIndex', slider.settings.slideZIndex);
  1325. updateAfterSlideTransition();
  1326. });
  1327. // slider mode is not "fade"
  1328. } else {
  1329. // if adaptiveHeight is true and next height is different from current height, animate to the new height
  1330. if (slider.settings.adaptiveHeight && slider.viewport.height() !== getViewportHeight()) {
  1331. slider.viewport.animate({height: getViewportHeight()}, slider.settings.adaptiveHeightSpeed);
  1332. }
  1333. // if carousel and not infinite loop
  1334. if (!slider.settings.infiniteLoop && slider.carousel && slider.active.last) {
  1335. if (slider.settings.mode === 'horizontal') {
  1336. // get the last child position
  1337. lastChild = slider.children.eq(slider.children.length - 1);
  1338. position = lastChild.position();
  1339. // calculate the position of the last slide
  1340. moveBy = slider.viewport.width() - lastChild.outerWidth();
  1341. } else {
  1342. // get last showing index position
  1343. lastShowingIndex = slider.children.length - slider.settings.minSlides;
  1344. position = slider.children.eq(lastShowingIndex).position();
  1345. }
  1346. // horizontal carousel, going previous while on first slide (infiniteLoop mode)
  1347. } else if (slider.carousel && slider.active.last && direction === 'prev') {
  1348. // get the last child position
  1349. eq = slider.settings.moveSlides === 1 ? slider.settings.maxSlides - getMoveBy() : ((getPagerQty() - 1) * getMoveBy()) - (slider.children.length - slider.settings.maxSlides);
  1350. lastChild = el.children('.bx-clone').eq(eq);
  1351. position = lastChild.position();
  1352. // if infinite loop and "Next" is clicked on the last slide
  1353. } else if (direction === 'next' && slider.active.index === 0) {
  1354. // get the last clone position
  1355. position = el.find('> .bx-clone').eq(slider.settings.maxSlides).position();
  1356. slider.active.last = false;
  1357. // normal non-zero requests
  1358. } else if (slideIndex >= 0) {
  1359. //parseInt is applied to allow floats for slides/page
  1360. requestEl = slideIndex * parseInt(getMoveBy());
  1361. position = slider.children.eq(requestEl).position();
  1362. }
  1363. /* If the position doesn't exist
  1364. * (e.g. if you destroy the slider on a next click),
  1365. * it doesn't throw an error.
  1366. */
  1367. if (typeof (position) !== 'undefined') {
  1368. value = slider.settings.mode === 'horizontal' ? -(position.left - moveBy) : -position.top;
  1369. // plugin values to be animated
  1370. setPositionProperty(value, 'slide', slider.settings.speed);
  1371. } else {
  1372. slider.working = false;
  1373. }
  1374. }
  1375. if (slider.settings.ariaHidden) { applyAriaHiddenAttributes(slider.active.index * getMoveBy()); }
  1376. };
  1377. /**
  1378. * Transitions to the next slide in the show
  1379. */
  1380. el.goToNextSlide = function() {
  1381. // if infiniteLoop is false and last page is showing, disregard call
  1382. if (!slider.settings.infiniteLoop && slider.active.last) { return; }
  1383. var pagerIndex = parseInt(slider.active.index) + 1;
  1384. el.goToSlide(pagerIndex, 'next');
  1385. };
  1386. /**
  1387. * Transitions to the prev slide in the show
  1388. */
  1389. el.goToPrevSlide = function() {
  1390. // if infiniteLoop is false and last page is showing, disregard call
  1391. if (!slider.settings.infiniteLoop && slider.active.index === 0) { return; }
  1392. var pagerIndex = parseInt(slider.active.index) - 1;
  1393. el.goToSlide(pagerIndex, 'prev');
  1394. };
  1395. /**
  1396. * Starts the auto show
  1397. *
  1398. * @param preventControlUpdate (boolean)
  1399. * - if true, auto controls state will not be updated
  1400. */
  1401. el.startAuto = function(preventControlUpdate) {
  1402. // if an interval already exists, disregard call
  1403. if (slider.interval) { return; }
  1404. // create an interval
  1405. slider.interval = setInterval(function() {
  1406. if (slider.settings.autoDirection === 'next') {
  1407. el.goToNextSlide();
  1408. } else {
  1409. el.goToPrevSlide();
  1410. }
  1411. }, slider.settings.pause);
  1412. // if auto controls are displayed and preventControlUpdate is not true
  1413. if (slider.settings.autoControls && preventControlUpdate !== true) { updateAutoControls('stop'); }
  1414. };
  1415. /**
  1416. * Stops the auto show
  1417. *
  1418. * @param preventControlUpdate (boolean)
  1419. * - if true, auto controls state will not be updated
  1420. */
  1421. el.stopAuto = function(preventControlUpdate) {
  1422. // if no interval exists, disregard call
  1423. if (!slider.interval) { return; }
  1424. // clear the interval
  1425. clearInterval(slider.interval);
  1426. slider.interval = null;
  1427. // if auto controls are displayed and preventControlUpdate is not true
  1428. if (slider.settings.autoControls && preventControlUpdate !== true) { updateAutoControls('start'); }
  1429. };
  1430. /**
  1431. * Returns current slide index (zero-based)
  1432. */
  1433. el.getCurrentSlide = function() {
  1434. return slider.active.index;
  1435. };
  1436. /**
  1437. * Returns current slide element
  1438. */
  1439. el.getCurrentSlideElement = function() {
  1440. return slider.children.eq(slider.active.index);
  1441. };
  1442. /**
  1443. * Returns a slide element
  1444. * @param index (int)
  1445. * - The index (zero-based) of the element you want returned.
  1446. */
  1447. el.getSlideElement = function(index) {
  1448. return slider.children.eq(index);
  1449. };
  1450. /**
  1451. * Returns number of slides in show
  1452. */
  1453. el.getSlideCount = function() {
  1454. return slider.children.length;
  1455. };
  1456. /**
  1457. * Return slider.working variable
  1458. */
  1459. el.isWorking = function() {
  1460. return slider.working;
  1461. };
  1462. /**
  1463. * Update all dynamic slider elements
  1464. */
  1465. el.redrawSlider = function() {
  1466. // resize all children in ratio to new screen size
  1467. slider.children.add(el.find('.bx-clone')).outerWidth(getSlideWidth());
  1468. // adjust the height
  1469. slider.viewport.css('height', getViewportHeight());
  1470. // update the slide position
  1471. if (!slider.settings.ticker) { setSlidePosition(); }
  1472. // if active.last was true before the screen resize, we want
  1473. // to keep it last no matter what screen size we end on
  1474. if (slider.active.last) { slider.active.index = getPagerQty() - 1; }
  1475. // if the active index (page) no longer exists due to the resize, simply set the index as last
  1476. if (slider.active.index >= getPagerQty()) { slider.active.last = true; }
  1477. // if a pager is being displayed and a custom pager is not being used, update it
  1478. if (slider.settings.pager && !slider.settings.pagerCustom) {
  1479. populatePager();
  1480. updatePagerActive(slider.active.index);
  1481. }
  1482. if (slider.settings.ariaHidden) { applyAriaHiddenAttributes(slider.active.index * getMoveBy()); }
  1483. };
  1484. /**
  1485. * Destroy the current instance of the slider (revert everything back to original state)
  1486. */
  1487. el.destroySlider = function() {
  1488. // don't do anything if slider has already been destroyed
  1489. if (!slider.initialized) { return; }
  1490. slider.initialized = false;
  1491. $('.bx-clone', this).remove();
  1492. slider.children.each(function() {
  1493. if ($(this).data('origStyle') !== undefined) {
  1494. $(this).attr('style', $(this).data('origStyle'));
  1495. } else {
  1496. $(this).removeAttr('style');
  1497. }
  1498. });
  1499. if ($(this).data('origStyle') !== undefined) {
  1500. this.attr('style', $(this).data('origStyle'));
  1501. } else {
  1502. $(this).removeAttr('style');
  1503. }
  1504. $(this).unwrap().unwrap();
  1505. if (slider.controls.el) { slider.controls.el.remove(); }
  1506. if (slider.controls.next) { slider.controls.next.remove(); }
  1507. if (slider.controls.prev) { slider.controls.prev.remove(); }
  1508. if (slider.pagerEl && slider.settings.controls && !slider.settings.pagerCustom) { slider.pagerEl.remove(); }
  1509. $('.bx-caption', this).remove();
  1510. if (slider.controls.autoEl) { slider.controls.autoEl.remove(); }
  1511. clearInterval(slider.interval);
  1512. if (slider.settings.responsive) { $(window).unbind('resize', resizeWindow); }
  1513. if (slider.settings.keyboardEnabled) { $(document).unbind('keydown', keyPress); }
  1514. //remove self reference in data
  1515. $(this).removeData('bxSlider');
  1516. };
  1517. /**
  1518. * Reload the slider (revert all DOM changes, and re-initialize)
  1519. */
  1520. el.reloadSlider = function(settings) {
  1521. if (settings !== undefined) { options = settings; }
  1522. el.destroySlider();
  1523. init();
  1524. //store reference to self in order to access public functions later
  1525. $(el).data('bxSlider', this);
  1526. };
  1527. init();
  1528. $(el).data('bxSlider', this);
  1529. // returns the current jQuery object
  1530. return this;
  1531. };
  1532. })(jQuery);