reveal.js 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328
  1. /*!
  2. * reveal.js
  3. * http://lab.hakim.se/reveal-js
  4. * MIT licensed
  5. *
  6. * Copyright (C) 2013 Hakim El Hattab, http://hakim.se
  7. */
  8. var Reveal = (function(){
  9. 'use strict';
  10. var SLIDES_SELECTOR = '.reveal .slides section',
  11. HORIZONTAL_SLIDES_SELECTOR = '.reveal .slides>section',
  12. VERTICAL_SLIDES_SELECTOR = '.reveal .slides>section.present>section',
  13. HOME_SLIDE_SELECTOR = '.reveal .slides>section:first-of-type',
  14. // Configurations defaults, can be overridden at initialization time
  15. config = {
  16. // The "normal" size of the presentation, aspect ratio will be preserved
  17. // when the presentation is scaled to fit different resolutions
  18. width: 960,
  19. height: 700,
  20. // Factor of the display size that should remain empty around the content
  21. margin: 0.1,
  22. // Bounds for smallest/largest possible scale to apply to content
  23. minScale: 0.2,
  24. maxScale: 1.0,
  25. // Display controls in the bottom right corner
  26. controls: true,
  27. // Display a presentation progress bar
  28. progress: true,
  29. // Display the page number of the current slide
  30. slideNumber: false,
  31. // Push each slide change to the browser history
  32. history: false,
  33. // Enable keyboard shortcuts for navigation
  34. keyboard: true,
  35. // Enable the slide overview mode
  36. overview: true,
  37. // Vertical centering of slides
  38. center: true,
  39. // Enables touch navigation on devices with touch input
  40. touch: true,
  41. // Loop the presentation
  42. loop: false,
  43. // Change the presentation direction to be RTL
  44. rtl: false,
  45. // Turns fragments on and off globally
  46. fragments: true,
  47. // Flags if the presentation is running in an embedded mode,
  48. // i.e. contained within a limited portion of the screen
  49. embedded: false,
  50. // Number of milliseconds between automatically proceeding to the
  51. // next slide, disabled when set to 0, this value can be overwritten
  52. // by using a data-autoslide attribute on your slides
  53. autoSlide: 0,
  54. // Stop auto-sliding after user input
  55. autoSlideStoppable: true,
  56. // Enable slide navigation via mouse wheel
  57. mouseWheel: false,
  58. // Apply a 3D roll to links on hover
  59. rollingLinks: false,
  60. // Hides the address bar on mobile devices
  61. hideAddressBar: true,
  62. // Opens links in an iframe preview overlay
  63. previewLinks: false,
  64. // Focuses body when page changes visiblity to ensure keyboard shortcuts work
  65. focusBodyOnPageVisiblityChange: true,
  66. // Theme (see /css/theme)
  67. theme: null,
  68. // Transition style
  69. transition: 'default', // default/cube/page/concave/zoom/linear/fade/none
  70. // Transition speed
  71. transitionSpeed: 'default', // default/fast/slow
  72. // Transition style for full page slide backgrounds
  73. backgroundTransition: 'default', // default/linear/none
  74. // Parallax background image
  75. parallaxBackgroundImage: '', // CSS syntax, e.g. "a.jpg"
  76. // Parallax background size
  77. parallaxBackgroundSize: '', // CSS syntax, e.g. "3000px 2000px"
  78. // Number of slides away from the current that are visible
  79. viewDistance: 3,
  80. // Script dependencies to load
  81. dependencies: []
  82. },
  83. // Flags if reveal.js is loaded (has dispatched the 'ready' event)
  84. loaded = false,
  85. // The horizontal and vertical index of the currently active slide
  86. indexh,
  87. indexv,
  88. // The previous and current slide HTML elements
  89. previousSlide,
  90. currentSlide,
  91. previousBackground,
  92. // Slides may hold a data-state attribute which we pick up and apply
  93. // as a class to the body. This list contains the combined state of
  94. // all current slides.
  95. state = [],
  96. // The current scale of the presentation (see width/height config)
  97. scale = 1,
  98. // Cached references to DOM elements
  99. dom = {},
  100. // Features supported by the browser, see #checkCapabilities()
  101. features = {},
  102. // Client is a mobile device, see #checkCapabilities()
  103. isMobileDevice,
  104. // Throttles mouse wheel navigation
  105. lastMouseWheelStep = 0,
  106. // Delays updates to the URL due to a Chrome thumbnailer bug
  107. writeURLTimeout = 0,
  108. // A delay used to activate the overview mode
  109. activateOverviewTimeout = 0,
  110. // A delay used to deactivate the overview mode
  111. deactivateOverviewTimeout = 0,
  112. // Flags if the interaction event listeners are bound
  113. eventsAreBound = false,
  114. // The current auto-slide duration
  115. autoSlide = 0,
  116. // Auto slide properties
  117. autoSlidePlayer,
  118. autoSlideTimeout = 0,
  119. autoSlideStartTime = -1,
  120. autoSlidePaused = false,
  121. // Holds information about the currently ongoing touch input
  122. touch = {
  123. startX: 0,
  124. startY: 0,
  125. startSpan: 0,
  126. startCount: 0,
  127. captured: false,
  128. threshold: 40
  129. };
  130. /**
  131. * Starts up the presentation if the client is capable.
  132. */
  133. function initialize( options ) {
  134. checkCapabilities();
  135. if( !features.transforms2d && !features.transforms3d ) {
  136. document.body.setAttribute( 'class', 'no-transforms' );
  137. // If the browser doesn't support core features we won't be
  138. // using JavaScript to control the presentation
  139. return;
  140. }
  141. // Force a layout when the whole page, incl fonts, has loaded
  142. window.addEventListener( 'load', layout, false );
  143. var query = Reveal.getQueryHash();
  144. // Do not accept new dependencies via query config to avoid
  145. // the potential of malicious script injection
  146. if( typeof query['dependencies'] !== 'undefined' ) delete query['dependencies'];
  147. // Copy options over to our config object
  148. extend( config, options );
  149. extend( config, query );
  150. // Hide the address bar in mobile browsers
  151. hideAddressBar();
  152. // Loads the dependencies and continues to #start() once done
  153. load();
  154. }
  155. /**
  156. * Inspect the client to see what it's capable of, this
  157. * should only happens once per runtime.
  158. */
  159. function checkCapabilities() {
  160. features.transforms3d = 'WebkitPerspective' in document.body.style ||
  161. 'MozPerspective' in document.body.style ||
  162. 'msPerspective' in document.body.style ||
  163. 'OPerspective' in document.body.style ||
  164. 'perspective' in document.body.style;
  165. features.transforms2d = 'WebkitTransform' in document.body.style ||
  166. 'MozTransform' in document.body.style ||
  167. 'msTransform' in document.body.style ||
  168. 'OTransform' in document.body.style ||
  169. 'transform' in document.body.style;
  170. features.requestAnimationFrameMethod = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame;
  171. features.requestAnimationFrame = typeof features.requestAnimationFrameMethod === 'function';
  172. features.canvas = !!document.createElement( 'canvas' ).getContext;
  173. isMobileDevice = navigator.userAgent.match( /(iphone|ipod|android)/gi );
  174. }
  175. /**
  176. * Loads the dependencies of reveal.js. Dependencies are
  177. * defined via the configuration option 'dependencies'
  178. * and will be loaded prior to starting/binding reveal.js.
  179. * Some dependencies may have an 'async' flag, if so they
  180. * will load after reveal.js has been started up.
  181. */
  182. function load() {
  183. var scripts = [],
  184. scriptsAsync = [];
  185. for( var i = 0, len = config.dependencies.length; i < len; i++ ) {
  186. var s = config.dependencies[i];
  187. // Load if there's no condition or the condition is truthy
  188. if( !s.condition || s.condition() ) {
  189. if( s.async ) {
  190. scriptsAsync.push( s.src );
  191. }
  192. else {
  193. scripts.push( s.src );
  194. }
  195. // Extension may contain callback functions
  196. if( typeof s.callback === 'function' ) {
  197. head.ready( s.src.match( /([\w\d_\-]*)\.?js$|[^\\\/]*$/i )[0], s.callback );
  198. }
  199. }
  200. }
  201. // Called once synchronous scripts finish loading
  202. function proceed() {
  203. if( scriptsAsync.length ) {
  204. // Load asynchronous scripts
  205. head.js.apply( null, scriptsAsync );
  206. }
  207. start();
  208. }
  209. if( scripts.length ) {
  210. head.ready( proceed );
  211. // Load synchronous scripts
  212. head.js.apply( null, scripts );
  213. }
  214. else {
  215. proceed();
  216. }
  217. }
  218. /**
  219. * Starts up reveal.js by binding input events and navigating
  220. * to the current URL deeplink if there is one.
  221. */
  222. function start() {
  223. // Make sure we've got all the DOM elements we need
  224. setupDOM();
  225. // Decorate the slide DOM elements with state classes (past/future)
  226. setupSlides();
  227. // Updates the presentation to match the current configuration values
  228. configure();
  229. // Read the initial hash
  230. readURL();
  231. // Update all backgrounds
  232. updateBackground( true );
  233. // Notify listeners that the presentation is ready but use a 1ms
  234. // timeout to ensure it's not fired synchronously after #initialize()
  235. setTimeout( function() {
  236. // Enable transitions now that we're loaded
  237. dom.slides.classList.remove( 'no-transition' );
  238. loaded = true;
  239. dispatchEvent( 'ready', {
  240. 'indexh': indexh,
  241. 'indexv': indexv,
  242. 'currentSlide': currentSlide
  243. } );
  244. }, 1 );
  245. }
  246. /**
  247. * Iterates through and decorates slides DOM elements with
  248. * appropriate classes.
  249. */
  250. function setupSlides() {
  251. var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
  252. horizontalSlides.forEach( function( horizontalSlide ) {
  253. var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
  254. verticalSlides.forEach( function( verticalSlide, y ) {
  255. if( y > 0 ) verticalSlide.classList.add( 'future' );
  256. } );
  257. } );
  258. }
  259. /**
  260. * Finds and stores references to DOM elements which are
  261. * required by the presentation. If a required element is
  262. * not found, it is created.
  263. */
  264. function setupDOM() {
  265. // Cache references to key DOM elements
  266. dom.theme = document.querySelector( '#theme' );
  267. dom.wrapper = document.querySelector( '.reveal' );
  268. dom.slides = document.querySelector( '.reveal .slides' );
  269. // Prevent transitions while we're loading
  270. dom.slides.classList.add( 'no-transition' );
  271. // Background element
  272. dom.background = createSingletonNode( dom.wrapper, 'div', 'backgrounds', null );
  273. // Progress bar
  274. dom.progress = createSingletonNode( dom.wrapper, 'div', 'progress', '<span></span>' );
  275. dom.progressbar = dom.progress.querySelector( 'span' );
  276. // Arrow controls
  277. createSingletonNode( dom.wrapper, 'aside', 'controls',
  278. '<div class="navigate-left"></div>' +
  279. '<div class="navigate-right"></div>' +
  280. '<div class="navigate-up"></div>' +
  281. '<div class="navigate-down"></div>' );
  282. // Slide number
  283. dom.slideNumber = createSingletonNode( dom.wrapper, 'div', 'slide-number', '' );
  284. // State background element [DEPRECATED]
  285. createSingletonNode( dom.wrapper, 'div', 'state-background', null );
  286. // Overlay graphic which is displayed during the paused mode
  287. createSingletonNode( dom.wrapper, 'div', 'pause-overlay', null );
  288. // Cache references to elements
  289. dom.controls = document.querySelector( '.reveal .controls' );
  290. // There can be multiple instances of controls throughout the page
  291. dom.controlsLeft = toArray( document.querySelectorAll( '.navigate-left' ) );
  292. dom.controlsRight = toArray( document.querySelectorAll( '.navigate-right' ) );
  293. dom.controlsUp = toArray( document.querySelectorAll( '.navigate-up' ) );
  294. dom.controlsDown = toArray( document.querySelectorAll( '.navigate-down' ) );
  295. dom.controlsPrev = toArray( document.querySelectorAll( '.navigate-prev' ) );
  296. dom.controlsNext = toArray( document.querySelectorAll( '.navigate-next' ) );
  297. }
  298. /**
  299. * Creates an HTML element and returns a reference to it.
  300. * If the element already exists the existing instance will
  301. * be returned.
  302. */
  303. function createSingletonNode( container, tagname, classname, innerHTML ) {
  304. var node = container.querySelector( '.' + classname );
  305. if( !node ) {
  306. node = document.createElement( tagname );
  307. node.classList.add( classname );
  308. if( innerHTML !== null ) {
  309. node.innerHTML = innerHTML;
  310. }
  311. container.appendChild( node );
  312. }
  313. return node;
  314. }
  315. /**
  316. * Creates the slide background elements and appends them
  317. * to the background container. One element is created per
  318. * slide no matter if the given slide has visible background.
  319. */
  320. function createBackgrounds() {
  321. if( isPrintingPDF() ) {
  322. document.body.classList.add( 'print-pdf' );
  323. }
  324. // Clear prior backgrounds
  325. dom.background.innerHTML = '';
  326. dom.background.classList.add( 'no-transition' );
  327. // Helper method for creating a background element for the
  328. // given slide
  329. function _createBackground( slide, container ) {
  330. var data = {
  331. background: slide.getAttribute( 'data-background' ),
  332. backgroundSize: slide.getAttribute( 'data-background-size' ),
  333. backgroundImage: slide.getAttribute( 'data-background-image' ),
  334. backgroundColor: slide.getAttribute( 'data-background-color' ),
  335. backgroundRepeat: slide.getAttribute( 'data-background-repeat' ),
  336. backgroundPosition: slide.getAttribute( 'data-background-position' ),
  337. backgroundTransition: slide.getAttribute( 'data-background-transition' )
  338. };
  339. var element = document.createElement( 'div' );
  340. element.className = 'slide-background';
  341. if( data.background ) {
  342. // Auto-wrap image urls in url(...)
  343. if( /^(http|file|\/\/)/gi.test( data.background ) || /\.(svg|png|jpg|jpeg|gif|bmp)$/gi.test( data.background ) ) {
  344. element.style.backgroundImage = 'url('+ data.background +')';
  345. }
  346. else {
  347. element.style.background = data.background;
  348. }
  349. }
  350. if( data.background || data.backgroundColor || data.backgroundImage ) {
  351. element.setAttribute( 'data-background-hash', data.background + data.backgroundSize + data.backgroundImage + data.backgroundColor + data.backgroundRepeat + data.backgroundPosition + data.backgroundTransition );
  352. }
  353. // Additional and optional background properties
  354. if( data.backgroundSize ) element.style.backgroundSize = data.backgroundSize;
  355. if( data.backgroundImage ) element.style.backgroundImage = 'url("' + data.backgroundImage + '")';
  356. if( data.backgroundColor ) element.style.backgroundColor = data.backgroundColor;
  357. if( data.backgroundRepeat ) element.style.backgroundRepeat = data.backgroundRepeat;
  358. if( data.backgroundPosition ) element.style.backgroundPosition = data.backgroundPosition;
  359. if( data.backgroundTransition ) element.setAttribute( 'data-background-transition', data.backgroundTransition );
  360. container.appendChild( element );
  361. return element;
  362. }
  363. // Iterate over all horizontal slides
  364. toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( slideh ) {
  365. var backgroundStack;
  366. if( isPrintingPDF() ) {
  367. backgroundStack = _createBackground( slideh, slideh );
  368. }
  369. else {
  370. backgroundStack = _createBackground( slideh, dom.background );
  371. }
  372. // Iterate over all vertical slides
  373. toArray( slideh.querySelectorAll( 'section' ) ).forEach( function( slidev ) {
  374. if( isPrintingPDF() ) {
  375. _createBackground( slidev, slidev );
  376. }
  377. else {
  378. _createBackground( slidev, backgroundStack );
  379. }
  380. } );
  381. } );
  382. // Add parallax background if specified
  383. if( config.parallaxBackgroundImage ) {
  384. dom.background.style.backgroundImage = 'url("' + config.parallaxBackgroundImage + '")';
  385. dom.background.style.backgroundSize = config.parallaxBackgroundSize;
  386. // Make sure the below properties are set on the element - these properties are
  387. // needed for proper transitions to be set on the element via CSS. To remove
  388. // annoying background slide-in effect when the presentation starts, apply
  389. // these properties after short time delay
  390. setTimeout( function() {
  391. dom.wrapper.classList.add( 'has-parallax-background' );
  392. }, 1 );
  393. }
  394. else {
  395. dom.background.style.backgroundImage = '';
  396. dom.wrapper.classList.remove( 'has-parallax-background' );
  397. }
  398. }
  399. /**
  400. * Applies the configuration settings from the config
  401. * object. May be called multiple times.
  402. */
  403. function configure( options ) {
  404. var numberOfSlides = document.querySelectorAll( SLIDES_SELECTOR ).length;
  405. dom.wrapper.classList.remove( config.transition );
  406. // New config options may be passed when this method
  407. // is invoked through the API after initialization
  408. if( typeof options === 'object' ) extend( config, options );
  409. // Force linear transition based on browser capabilities
  410. if( features.transforms3d === false ) config.transition = 'linear';
  411. dom.wrapper.classList.add( config.transition );
  412. dom.wrapper.setAttribute( 'data-transition-speed', config.transitionSpeed );
  413. dom.wrapper.setAttribute( 'data-background-transition', config.backgroundTransition );
  414. dom.controls.style.display = config.controls ? 'block' : 'none';
  415. dom.progress.style.display = config.progress ? 'block' : 'none';
  416. if( config.rtl ) {
  417. dom.wrapper.classList.add( 'rtl' );
  418. }
  419. else {
  420. dom.wrapper.classList.remove( 'rtl' );
  421. }
  422. if( config.center ) {
  423. dom.wrapper.classList.add( 'center' );
  424. }
  425. else {
  426. dom.wrapper.classList.remove( 'center' );
  427. }
  428. if( config.mouseWheel ) {
  429. document.addEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
  430. document.addEventListener( 'mousewheel', onDocumentMouseScroll, false );
  431. }
  432. else {
  433. document.removeEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
  434. document.removeEventListener( 'mousewheel', onDocumentMouseScroll, false );
  435. }
  436. // Rolling 3D links
  437. if( config.rollingLinks ) {
  438. enableRollingLinks();
  439. }
  440. else {
  441. disableRollingLinks();
  442. }
  443. // Iframe link previews
  444. if( config.previewLinks ) {
  445. enablePreviewLinks();
  446. }
  447. else {
  448. disablePreviewLinks();
  449. enablePreviewLinks( '[data-preview-link]' );
  450. }
  451. // Auto-slide playback controls
  452. if( numberOfSlides > 1 && config.autoSlide && config.autoSlideStoppable && features.canvas && features.requestAnimationFrame ) {
  453. autoSlidePlayer = new Playback( dom.wrapper, function() {
  454. return Math.min( Math.max( ( Date.now() - autoSlideStartTime ) / autoSlide, 0 ), 1 );
  455. } );
  456. autoSlidePlayer.on( 'click', onAutoSlidePlayerClick );
  457. autoSlidePaused = false;
  458. }
  459. else if( autoSlidePlayer ) {
  460. autoSlidePlayer.destroy();
  461. autoSlidePlayer = null;
  462. }
  463. // Load the theme in the config, if it's not already loaded
  464. if( config.theme && dom.theme ) {
  465. var themeURL = dom.theme.getAttribute( 'href' );
  466. var themeFinder = /[^\/]*?(?=\.css)/;
  467. var themeName = themeURL.match(themeFinder)[0];
  468. if( config.theme !== themeName ) {
  469. themeURL = themeURL.replace(themeFinder, config.theme);
  470. dom.theme.setAttribute( 'href', themeURL );
  471. }
  472. }
  473. sync();
  474. }
  475. /**
  476. * Binds all event listeners.
  477. */
  478. function addEventListeners() {
  479. eventsAreBound = true;
  480. window.addEventListener( 'hashchange', onWindowHashChange, false );
  481. window.addEventListener( 'resize', onWindowResize, false );
  482. if( config.touch ) {
  483. dom.wrapper.addEventListener( 'touchstart', onTouchStart, false );
  484. dom.wrapper.addEventListener( 'touchmove', onTouchMove, false );
  485. dom.wrapper.addEventListener( 'touchend', onTouchEnd, false );
  486. // Support pointer-style touch interaction as well
  487. if( window.navigator.msPointerEnabled ) {
  488. dom.wrapper.addEventListener( 'MSPointerDown', onPointerDown, false );
  489. dom.wrapper.addEventListener( 'MSPointerMove', onPointerMove, false );
  490. dom.wrapper.addEventListener( 'MSPointerUp', onPointerUp, false );
  491. }
  492. }
  493. if( config.keyboard ) {
  494. document.addEventListener( 'keydown', onDocumentKeyDown, false );
  495. }
  496. if( config.progress && dom.progress ) {
  497. dom.progress.addEventListener( 'click', onProgressClicked, false );
  498. }
  499. if( config.focusBodyOnPageVisiblityChange ) {
  500. var visibilityChange;
  501. if( 'hidden' in document ) {
  502. visibilityChange = 'visibilitychange';
  503. }
  504. else if( 'msHidden' in document ) {
  505. visibilityChange = 'msvisibilitychange';
  506. }
  507. else if( 'webkitHidden' in document ) {
  508. visibilityChange = 'webkitvisibilitychange';
  509. }
  510. if( visibilityChange ) {
  511. document.addEventListener( visibilityChange, onPageVisibilityChange, false );
  512. }
  513. }
  514. [ 'touchstart', 'click' ].forEach( function( eventName ) {
  515. dom.controlsLeft.forEach( function( el ) { el.addEventListener( eventName, onNavigateLeftClicked, false ); } );
  516. dom.controlsRight.forEach( function( el ) { el.addEventListener( eventName, onNavigateRightClicked, false ); } );
  517. dom.controlsUp.forEach( function( el ) { el.addEventListener( eventName, onNavigateUpClicked, false ); } );
  518. dom.controlsDown.forEach( function( el ) { el.addEventListener( eventName, onNavigateDownClicked, false ); } );
  519. dom.controlsPrev.forEach( function( el ) { el.addEventListener( eventName, onNavigatePrevClicked, false ); } );
  520. dom.controlsNext.forEach( function( el ) { el.addEventListener( eventName, onNavigateNextClicked, false ); } );
  521. } );
  522. }
  523. /**
  524. * Unbinds all event listeners.
  525. */
  526. function removeEventListeners() {
  527. eventsAreBound = false;
  528. document.removeEventListener( 'keydown', onDocumentKeyDown, false );
  529. window.removeEventListener( 'hashchange', onWindowHashChange, false );
  530. window.removeEventListener( 'resize', onWindowResize, false );
  531. dom.wrapper.removeEventListener( 'touchstart', onTouchStart, false );
  532. dom.wrapper.removeEventListener( 'touchmove', onTouchMove, false );
  533. dom.wrapper.removeEventListener( 'touchend', onTouchEnd, false );
  534. if( window.navigator.msPointerEnabled ) {
  535. dom.wrapper.removeEventListener( 'MSPointerDown', onPointerDown, false );
  536. dom.wrapper.removeEventListener( 'MSPointerMove', onPointerMove, false );
  537. dom.wrapper.removeEventListener( 'MSPointerUp', onPointerUp, false );
  538. }
  539. if ( config.progress && dom.progress ) {
  540. dom.progress.removeEventListener( 'click', onProgressClicked, false );
  541. }
  542. [ 'touchstart', 'click' ].forEach( function( eventName ) {
  543. dom.controlsLeft.forEach( function( el ) { el.removeEventListener( eventName, onNavigateLeftClicked, false ); } );
  544. dom.controlsRight.forEach( function( el ) { el.removeEventListener( eventName, onNavigateRightClicked, false ); } );
  545. dom.controlsUp.forEach( function( el ) { el.removeEventListener( eventName, onNavigateUpClicked, false ); } );
  546. dom.controlsDown.forEach( function( el ) { el.removeEventListener( eventName, onNavigateDownClicked, false ); } );
  547. dom.controlsPrev.forEach( function( el ) { el.removeEventListener( eventName, onNavigatePrevClicked, false ); } );
  548. dom.controlsNext.forEach( function( el ) { el.removeEventListener( eventName, onNavigateNextClicked, false ); } );
  549. } );
  550. }
  551. /**
  552. * Extend object a with the properties of object b.
  553. * If there's a conflict, object b takes precedence.
  554. */
  555. function extend( a, b ) {
  556. for( var i in b ) {
  557. a[ i ] = b[ i ];
  558. }
  559. }
  560. /**
  561. * Converts the target object to an array.
  562. */
  563. function toArray( o ) {
  564. return Array.prototype.slice.call( o );
  565. }
  566. /**
  567. * Measures the distance in pixels between point a
  568. * and point b.
  569. *
  570. * @param {Object} a point with x/y properties
  571. * @param {Object} b point with x/y properties
  572. */
  573. function distanceBetween( a, b ) {
  574. var dx = a.x - b.x,
  575. dy = a.y - b.y;
  576. return Math.sqrt( dx*dx + dy*dy );
  577. }
  578. /**
  579. * Applies a CSS transform to the target element.
  580. */
  581. function transformElement( element, transform ) {
  582. element.style.WebkitTransform = transform;
  583. element.style.MozTransform = transform;
  584. element.style.msTransform = transform;
  585. element.style.OTransform = transform;
  586. element.style.transform = transform;
  587. }
  588. /**
  589. * Retrieves the height of the given element by looking
  590. * at the position and height of its immediate children.
  591. */
  592. function getAbsoluteHeight( element ) {
  593. var height = 0;
  594. if( element ) {
  595. var absoluteChildren = 0;
  596. toArray( element.childNodes ).forEach( function( child ) {
  597. if( typeof child.offsetTop === 'number' && child.style ) {
  598. // Count # of abs children
  599. if( child.style.position === 'absolute' ) {
  600. absoluteChildren += 1;
  601. }
  602. height = Math.max( height, child.offsetTop + child.offsetHeight );
  603. }
  604. } );
  605. // If there are no absolute children, use offsetHeight
  606. if( absoluteChildren === 0 ) {
  607. height = element.offsetHeight;
  608. }
  609. }
  610. return height;
  611. }
  612. /**
  613. * Returns the remaining height within the parent of the
  614. * target element after subtracting the height of all
  615. * siblings.
  616. *
  617. * remaining height = [parent height] - [ siblings height]
  618. */
  619. function getRemainingHeight( element, height ) {
  620. height = height || 0;
  621. if( element ) {
  622. var parent = element.parentNode;
  623. var siblings = parent.childNodes;
  624. // Subtract the height of each sibling
  625. toArray( siblings ).forEach( function( sibling ) {
  626. if( typeof sibling.offsetHeight === 'number' && sibling !== element ) {
  627. var styles = window.getComputedStyle( sibling ),
  628. marginTop = parseInt( styles.marginTop, 10 ),
  629. marginBottom = parseInt( styles.marginBottom, 10 );
  630. height -= sibling.offsetHeight + marginTop + marginBottom;
  631. }
  632. } );
  633. var elementStyles = window.getComputedStyle( element );
  634. // Subtract the margins of the target element
  635. height -= parseInt( elementStyles.marginTop, 10 ) +
  636. parseInt( elementStyles.marginBottom, 10 );
  637. }
  638. return height;
  639. }
  640. /**
  641. * Checks if this instance is being used to print a PDF.
  642. */
  643. function isPrintingPDF() {
  644. return ( /print-pdf/gi ).test( window.location.search );
  645. }
  646. /**
  647. * Hides the address bar if we're on a mobile device.
  648. */
  649. function hideAddressBar() {
  650. if( config.hideAddressBar && isMobileDevice ) {
  651. // Events that should trigger the address bar to hide
  652. window.addEventListener( 'load', removeAddressBar, false );
  653. window.addEventListener( 'orientationchange', removeAddressBar, false );
  654. }
  655. }
  656. /**
  657. * Causes the address bar to hide on mobile devices,
  658. * more vertical space ftw.
  659. */
  660. function removeAddressBar() {
  661. setTimeout( function() {
  662. window.scrollTo( 0, 1 );
  663. }, 10 );
  664. }
  665. /**
  666. * Dispatches an event of the specified type from the
  667. * reveal DOM element.
  668. */
  669. function dispatchEvent( type, properties ) {
  670. var event = document.createEvent( "HTMLEvents", 1, 2 );
  671. event.initEvent( type, true, true );
  672. extend( event, properties );
  673. dom.wrapper.dispatchEvent( event );
  674. }
  675. /**
  676. * Wrap all links in 3D goodness.
  677. */
  678. function enableRollingLinks() {
  679. if( features.transforms3d && !( 'msPerspective' in document.body.style ) ) {
  680. var anchors = document.querySelectorAll( SLIDES_SELECTOR + ' a:not(.image)' );
  681. for( var i = 0, len = anchors.length; i < len; i++ ) {
  682. var anchor = anchors[i];
  683. if( anchor.textContent && !anchor.querySelector( '*' ) && ( !anchor.className || !anchor.classList.contains( anchor, 'roll' ) ) ) {
  684. var span = document.createElement('span');
  685. span.setAttribute('data-title', anchor.text);
  686. span.innerHTML = anchor.innerHTML;
  687. anchor.classList.add( 'roll' );
  688. anchor.innerHTML = '';
  689. anchor.appendChild(span);
  690. }
  691. }
  692. }
  693. }
  694. /**
  695. * Unwrap all 3D links.
  696. */
  697. function disableRollingLinks() {
  698. var anchors = document.querySelectorAll( SLIDES_SELECTOR + ' a.roll' );
  699. for( var i = 0, len = anchors.length; i < len; i++ ) {
  700. var anchor = anchors[i];
  701. var span = anchor.querySelector( 'span' );
  702. if( span ) {
  703. anchor.classList.remove( 'roll' );
  704. anchor.innerHTML = span.innerHTML;
  705. }
  706. }
  707. }
  708. /**
  709. * Bind preview frame links.
  710. */
  711. function enablePreviewLinks( selector ) {
  712. var anchors = toArray( document.querySelectorAll( selector ? selector : 'a' ) );
  713. anchors.forEach( function( element ) {
  714. if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) {
  715. element.addEventListener( 'click', onPreviewLinkClicked, false );
  716. }
  717. } );
  718. }
  719. /**
  720. * Unbind preview frame links.
  721. */
  722. function disablePreviewLinks() {
  723. var anchors = toArray( document.querySelectorAll( 'a' ) );
  724. anchors.forEach( function( element ) {
  725. if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) {
  726. element.removeEventListener( 'click', onPreviewLinkClicked, false );
  727. }
  728. } );
  729. }
  730. /**
  731. * Opens a preview window for the target URL.
  732. */
  733. function openPreview( url ) {
  734. closePreview();
  735. dom.preview = document.createElement( 'div' );
  736. dom.preview.classList.add( 'preview-link-overlay' );
  737. dom.wrapper.appendChild( dom.preview );
  738. dom.preview.innerHTML = [
  739. '<header>',
  740. '<a class="close" href="#"><span class="icon"></span></a>',
  741. '<a class="external" href="'+ url +'" target="_blank"><span class="icon"></span></a>',
  742. '</header>',
  743. '<div class="spinner"></div>',
  744. '<div class="viewport">',
  745. '<iframe src="'+ url +'"></iframe>',
  746. '</div>'
  747. ].join('');
  748. dom.preview.querySelector( 'iframe' ).addEventListener( 'load', function( event ) {
  749. dom.preview.classList.add( 'loaded' );
  750. }, false );
  751. dom.preview.querySelector( '.close' ).addEventListener( 'click', function( event ) {
  752. closePreview();
  753. event.preventDefault();
  754. }, false );
  755. dom.preview.querySelector( '.external' ).addEventListener( 'click', function( event ) {
  756. closePreview();
  757. }, false );
  758. setTimeout( function() {
  759. dom.preview.classList.add( 'visible' );
  760. }, 1 );
  761. }
  762. /**
  763. * Closes the iframe preview window.
  764. */
  765. function closePreview() {
  766. if( dom.preview ) {
  767. dom.preview.setAttribute( 'src', '' );
  768. dom.preview.parentNode.removeChild( dom.preview );
  769. dom.preview = null;
  770. }
  771. }
  772. /**
  773. * Return a sorted fragments list, ordered by an increasing
  774. * "data-fragment-index" attribute.
  775. *
  776. * Fragments will be revealed in the order that they are returned by
  777. * this function, so you can use the index attributes to control the
  778. * order of fragment appearance.
  779. *
  780. * To maintain a sensible default fragment order, fragments are presumed
  781. * to be passed in document order. This function adds a "fragment-index"
  782. * attribute to each node if such an attribute is not already present,
  783. * and sets that attribute to an integer value which is the position of
  784. * the fragment within the fragments list.
  785. */
  786. function sortFragments( fragments ) {
  787. fragments = toArray( fragments );
  788. var ordered = [],
  789. unordered = [],
  790. sorted = [];
  791. // Group ordered and unordered elements
  792. fragments.forEach( function( fragment, i ) {
  793. if( fragment.hasAttribute( 'data-fragment-index' ) ) {
  794. var index = parseInt( fragment.getAttribute( 'data-fragment-index' ), 10 );
  795. if( !ordered[index] ) {
  796. ordered[index] = [];
  797. }
  798. ordered[index].push( fragment );
  799. }
  800. else {
  801. unordered.push( [ fragment ] );
  802. }
  803. } );
  804. // Append fragments without explicit indices in their
  805. // DOM order
  806. ordered = ordered.concat( unordered );
  807. // Manually count the index up per group to ensure there
  808. // are no gaps
  809. var index = 0;
  810. // Push all fragments in their sorted order to an array,
  811. // this flattens the groups
  812. ordered.forEach( function( group ) {
  813. group.forEach( function( fragment ) {
  814. sorted.push( fragment );
  815. fragment.setAttribute( 'data-fragment-index', index );
  816. } );
  817. index ++;
  818. } );
  819. return sorted;
  820. }
  821. /**
  822. * Applies JavaScript-controlled layout rules to the
  823. * presentation.
  824. */
  825. function layout() {
  826. if( dom.wrapper && !isPrintingPDF() ) {
  827. // Available space to scale within
  828. var availableWidth = dom.wrapper.offsetWidth,
  829. availableHeight = dom.wrapper.offsetHeight;
  830. // Reduce available space by margin
  831. availableWidth -= ( availableHeight * config.margin );
  832. availableHeight -= ( availableHeight * config.margin );
  833. // Dimensions of the content
  834. var slideWidth = config.width,
  835. slideHeight = config.height,
  836. slidePadding = 20; // TODO Dig this out of DOM
  837. // Layout the contents of the slides
  838. layoutSlideContents( config.width, config.height, slidePadding );
  839. // Slide width may be a percentage of available width
  840. if( typeof slideWidth === 'string' && /%$/.test( slideWidth ) ) {
  841. slideWidth = parseInt( slideWidth, 10 ) / 100 * availableWidth;
  842. }
  843. // Slide height may be a percentage of available height
  844. if( typeof slideHeight === 'string' && /%$/.test( slideHeight ) ) {
  845. slideHeight = parseInt( slideHeight, 10 ) / 100 * availableHeight;
  846. }
  847. dom.slides.style.width = slideWidth + 'px';
  848. dom.slides.style.height = slideHeight + 'px';
  849. // Determine scale of content to fit within available space
  850. scale = Math.min( availableWidth / slideWidth, availableHeight / slideHeight );
  851. // Respect max/min scale settings
  852. scale = Math.max( scale, config.minScale );
  853. scale = Math.min( scale, config.maxScale );
  854. // Prefer applying scale via zoom since Chrome blurs scaled content
  855. // with nested transforms
  856. if( typeof dom.slides.style.zoom !== 'undefined' && !navigator.userAgent.match( /(iphone|ipod|ipad|android)/gi ) ) {
  857. dom.slides.style.zoom = scale;
  858. }
  859. // Apply scale transform as a fallback
  860. else {
  861. transformElement( dom.slides, 'translate(-50%, -50%) scale('+ scale +') translate(50%, 50%)' );
  862. }
  863. // Select all slides, vertical and horizontal
  864. var slides = toArray( document.querySelectorAll( SLIDES_SELECTOR ) );
  865. for( var i = 0, len = slides.length; i < len; i++ ) {
  866. var slide = slides[ i ];
  867. // Don't bother updating invisible slides
  868. if( slide.style.display === 'none' ) {
  869. continue;
  870. }
  871. if( config.center || slide.classList.contains( 'center' ) ) {
  872. // Vertical stacks are not centred since their section
  873. // children will be
  874. if( slide.classList.contains( 'stack' ) ) {
  875. slide.style.top = 0;
  876. }
  877. else {
  878. slide.style.top = Math.max( - ( getAbsoluteHeight( slide ) / 2 ) - slidePadding, -slideHeight / 2 ) + 'px';
  879. }
  880. }
  881. else {
  882. slide.style.top = '';
  883. }
  884. }
  885. updateProgress();
  886. updateParallax();
  887. }
  888. }
  889. /**
  890. * Applies layout logic to the contents of all slides in
  891. * the presentation.
  892. */
  893. function layoutSlideContents( width, height, padding ) {
  894. // Handle sizing of elements with the 'stretch' class
  895. toArray( dom.slides.querySelectorAll( 'section > .stretch' ) ).forEach( function( element ) {
  896. // Determine how much vertical space we can use
  897. var remainingHeight = getRemainingHeight( element, ( height - ( padding * 2 ) ) );
  898. // Consider the aspect ratio of media elements
  899. if( /(img|video)/gi.test( element.nodeName ) ) {
  900. var nw = element.naturalWidth || element.videoWidth,
  901. nh = element.naturalHeight || element.videoHeight;
  902. var es = Math.min( width / nw, remainingHeight / nh );
  903. element.style.width = ( nw * es ) + 'px';
  904. element.style.height = ( nh * es ) + 'px';
  905. }
  906. else {
  907. element.style.width = width + 'px';
  908. element.style.height = remainingHeight + 'px';
  909. }
  910. } );
  911. }
  912. /**
  913. * Stores the vertical index of a stack so that the same
  914. * vertical slide can be selected when navigating to and
  915. * from the stack.
  916. *
  917. * @param {HTMLElement} stack The vertical stack element
  918. * @param {int} v Index to memorize
  919. */
  920. function setPreviousVerticalIndex( stack, v ) {
  921. if( typeof stack === 'object' && typeof stack.setAttribute === 'function' ) {
  922. stack.setAttribute( 'data-previous-indexv', v || 0 );
  923. }
  924. }
  925. /**
  926. * Retrieves the vertical index which was stored using
  927. * #setPreviousVerticalIndex() or 0 if no previous index
  928. * exists.
  929. *
  930. * @param {HTMLElement} stack The vertical stack element
  931. */
  932. function getPreviousVerticalIndex( stack ) {
  933. if( typeof stack === 'object' && typeof stack.setAttribute === 'function' && stack.classList.contains( 'stack' ) ) {
  934. // Prefer manually defined start-indexv
  935. var attributeName = stack.hasAttribute( 'data-start-indexv' ) ? 'data-start-indexv' : 'data-previous-indexv';
  936. return parseInt( stack.getAttribute( attributeName ) || 0, 10 );
  937. }
  938. return 0;
  939. }
  940. /**
  941. * Displays the overview of slides (quick nav) by
  942. * scaling down and arranging all slide elements.
  943. *
  944. * Experimental feature, might be dropped if perf
  945. * can't be improved.
  946. */
  947. function activateOverview() {
  948. // Only proceed if enabled in config
  949. if( config.overview ) {
  950. // Don't auto-slide while in overview mode
  951. cancelAutoSlide();
  952. var wasActive = dom.wrapper.classList.contains( 'overview' );
  953. // Vary the depth of the overview based on screen size
  954. var depth = window.innerWidth < 400 ? 1000 : 2500;
  955. dom.wrapper.classList.add( 'overview' );
  956. dom.wrapper.classList.remove( 'overview-deactivating' );
  957. clearTimeout( activateOverviewTimeout );
  958. clearTimeout( deactivateOverviewTimeout );
  959. // Not the pretties solution, but need to let the overview
  960. // class apply first so that slides are measured accurately
  961. // before we can position them
  962. activateOverviewTimeout = setTimeout( function() {
  963. var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
  964. for( var i = 0, len1 = horizontalSlides.length; i < len1; i++ ) {
  965. var hslide = horizontalSlides[i],
  966. hoffset = config.rtl ? -105 : 105;
  967. hslide.setAttribute( 'data-index-h', i );
  968. // Apply CSS transform
  969. transformElement( hslide, 'translateZ(-'+ depth +'px) translate(' + ( ( i - indexh ) * hoffset ) + '%, 0%)' );
  970. if( hslide.classList.contains( 'stack' ) ) {
  971. var verticalSlides = hslide.querySelectorAll( 'section' );
  972. for( var j = 0, len2 = verticalSlides.length; j < len2; j++ ) {
  973. var verticalIndex = i === indexh ? indexv : getPreviousVerticalIndex( hslide );
  974. var vslide = verticalSlides[j];
  975. vslide.setAttribute( 'data-index-h', i );
  976. vslide.setAttribute( 'data-index-v', j );
  977. // Apply CSS transform
  978. transformElement( vslide, 'translate(0%, ' + ( ( j - verticalIndex ) * 105 ) + '%)' );
  979. // Navigate to this slide on click
  980. vslide.addEventListener( 'click', onOverviewSlideClicked, true );
  981. }
  982. }
  983. else {
  984. // Navigate to this slide on click
  985. hslide.addEventListener( 'click', onOverviewSlideClicked, true );
  986. }
  987. }
  988. updateSlidesVisibility();
  989. layout();
  990. if( !wasActive ) {
  991. // Notify observers of the overview showing
  992. dispatchEvent( 'overviewshown', {
  993. 'indexh': indexh,
  994. 'indexv': indexv,
  995. 'currentSlide': currentSlide
  996. } );
  997. }
  998. }, 10 );
  999. }
  1000. }
  1001. /**
  1002. * Exits the slide overview and enters the currently
  1003. * active slide.
  1004. */
  1005. function deactivateOverview() {
  1006. // Only proceed if enabled in config
  1007. if( config.overview ) {
  1008. clearTimeout( activateOverviewTimeout );
  1009. clearTimeout( deactivateOverviewTimeout );
  1010. dom.wrapper.classList.remove( 'overview' );
  1011. // Temporarily add a class so that transitions can do different things
  1012. // depending on whether they are exiting/entering overview, or just
  1013. // moving from slide to slide
  1014. dom.wrapper.classList.add( 'overview-deactivating' );
  1015. deactivateOverviewTimeout = setTimeout( function () {
  1016. dom.wrapper.classList.remove( 'overview-deactivating' );
  1017. }, 1 );
  1018. // Select all slides
  1019. toArray( document.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) {
  1020. // Resets all transforms to use the external styles
  1021. transformElement( slide, '' );
  1022. slide.removeEventListener( 'click', onOverviewSlideClicked, true );
  1023. } );
  1024. slide( indexh, indexv );
  1025. cueAutoSlide();
  1026. // Notify observers of the overview hiding
  1027. dispatchEvent( 'overviewhidden', {
  1028. 'indexh': indexh,
  1029. 'indexv': indexv,
  1030. 'currentSlide': currentSlide
  1031. } );
  1032. }
  1033. }
  1034. /**
  1035. * Toggles the slide overview mode on and off.
  1036. *
  1037. * @param {Boolean} override Optional flag which overrides the
  1038. * toggle logic and forcibly sets the desired state. True means
  1039. * overview is open, false means it's closed.
  1040. */
  1041. function toggleOverview( override ) {
  1042. if( typeof override === 'boolean' ) {
  1043. override ? activateOverview() : deactivateOverview();
  1044. }
  1045. else {
  1046. isOverview() ? deactivateOverview() : activateOverview();
  1047. }
  1048. }
  1049. /**
  1050. * Checks if the overview is currently active.
  1051. *
  1052. * @return {Boolean} true if the overview is active,
  1053. * false otherwise
  1054. */
  1055. function isOverview() {
  1056. return dom.wrapper.classList.contains( 'overview' );
  1057. }
  1058. /**
  1059. * Checks if the current or specified slide is vertical
  1060. * (nested within another slide).
  1061. *
  1062. * @param {HTMLElement} slide [optional] The slide to check
  1063. * orientation of
  1064. */
  1065. function isVerticalSlide( slide ) {
  1066. // Prefer slide argument, otherwise use current slide
  1067. slide = slide ? slide : currentSlide;
  1068. return slide && slide.parentNode && !!slide.parentNode.nodeName.match( /section/i );
  1069. }
  1070. /**
  1071. * Handling the fullscreen functionality via the fullscreen API
  1072. *
  1073. * @see http://fullscreen.spec.whatwg.org/
  1074. * @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode
  1075. */
  1076. function enterFullscreen() {
  1077. var element = document.body;
  1078. // Check which implementation is available
  1079. var requestMethod = element.requestFullScreen ||
  1080. element.webkitRequestFullscreen ||
  1081. element.webkitRequestFullScreen ||
  1082. element.mozRequestFullScreen ||
  1083. element.msRequestFullScreen;
  1084. if( requestMethod ) {
  1085. requestMethod.apply( element );
  1086. }
  1087. }
  1088. /**
  1089. * Enters the paused mode which fades everything on screen to
  1090. * black.
  1091. */
  1092. function pause() {
  1093. var wasPaused = dom.wrapper.classList.contains( 'paused' );
  1094. cancelAutoSlide();
  1095. dom.wrapper.classList.add( 'paused' );
  1096. if( wasPaused === false ) {
  1097. dispatchEvent( 'paused' );
  1098. }
  1099. }
  1100. /**
  1101. * Exits from the paused mode.
  1102. */
  1103. function resume() {
  1104. var wasPaused = dom.wrapper.classList.contains( 'paused' );
  1105. dom.wrapper.classList.remove( 'paused' );
  1106. cueAutoSlide();
  1107. if( wasPaused ) {
  1108. dispatchEvent( 'resumed' );
  1109. }
  1110. }
  1111. /**
  1112. * Toggles the paused mode on and off.
  1113. */
  1114. function togglePause() {
  1115. if( isPaused() ) {
  1116. resume();
  1117. }
  1118. else {
  1119. pause();
  1120. }
  1121. }
  1122. /**
  1123. * Checks if we are currently in the paused mode.
  1124. */
  1125. function isPaused() {
  1126. return dom.wrapper.classList.contains( 'paused' );
  1127. }
  1128. /**
  1129. * Steps from the current point in the presentation to the
  1130. * slide which matches the specified horizontal and vertical
  1131. * indices.
  1132. *
  1133. * @param {int} h Horizontal index of the target slide
  1134. * @param {int} v Vertical index of the target slide
  1135. * @param {int} f Optional index of a fragment within the
  1136. * target slide to activate
  1137. * @param {int} o Optional origin for use in multimaster environments
  1138. */
  1139. function slide( h, v, f, o ) {
  1140. // Remember where we were at before
  1141. previousSlide = currentSlide;
  1142. // Query all horizontal slides in the deck
  1143. var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
  1144. // If no vertical index is specified and the upcoming slide is a
  1145. // stack, resume at its previous vertical index
  1146. if( v === undefined ) {
  1147. v = getPreviousVerticalIndex( horizontalSlides[ h ] );
  1148. }
  1149. // If we were on a vertical stack, remember what vertical index
  1150. // it was on so we can resume at the same position when returning
  1151. if( previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains( 'stack' ) ) {
  1152. setPreviousVerticalIndex( previousSlide.parentNode, indexv );
  1153. }
  1154. // Remember the state before this slide
  1155. var stateBefore = state.concat();
  1156. // Reset the state array
  1157. state.length = 0;
  1158. var indexhBefore = indexh || 0,
  1159. indexvBefore = indexv || 0;
  1160. // Activate and transition to the new slide
  1161. indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h );
  1162. indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v );
  1163. // Update the visibility of slides now that the indices have changed
  1164. updateSlidesVisibility();
  1165. layout();
  1166. // Apply the new state
  1167. stateLoop: for( var i = 0, len = state.length; i < len; i++ ) {
  1168. // Check if this state existed on the previous slide. If it
  1169. // did, we will avoid adding it repeatedly
  1170. for( var j = 0; j < stateBefore.length; j++ ) {
  1171. if( stateBefore[j] === state[i] ) {
  1172. stateBefore.splice( j, 1 );
  1173. continue stateLoop;
  1174. }
  1175. }
  1176. document.documentElement.classList.add( state[i] );
  1177. // Dispatch custom event matching the state's name
  1178. dispatchEvent( state[i] );
  1179. }
  1180. // Clean up the remains of the previous state
  1181. while( stateBefore.length ) {
  1182. document.documentElement.classList.remove( stateBefore.pop() );
  1183. }
  1184. // If the overview is active, re-activate it to update positions
  1185. if( isOverview() ) {
  1186. activateOverview();
  1187. }
  1188. // Find the current horizontal slide and any possible vertical slides
  1189. // within it
  1190. var currentHorizontalSlide = horizontalSlides[ indexh ],
  1191. currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' );
  1192. // Store references to the previous and current slides
  1193. currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide;
  1194. // Show fragment, if specified
  1195. if( typeof f !== 'undefined' ) {
  1196. navigateFragment( f );
  1197. }
  1198. // Dispatch an event if the slide changed
  1199. var slideChanged = ( indexh !== indexhBefore || indexv !== indexvBefore );
  1200. if( slideChanged ) {
  1201. dispatchEvent( 'slidechanged', {
  1202. 'indexh': indexh,
  1203. 'indexv': indexv,
  1204. 'previousSlide': previousSlide,
  1205. 'currentSlide': currentSlide,
  1206. 'origin': o
  1207. } );
  1208. }
  1209. else {
  1210. // Ensure that the previous slide is never the same as the current
  1211. previousSlide = null;
  1212. }
  1213. // Solves an edge case where the previous slide maintains the
  1214. // 'present' class when navigating between adjacent vertical
  1215. // stacks
  1216. if( previousSlide ) {
  1217. previousSlide.classList.remove( 'present' );
  1218. // Reset all slides upon navigate to home
  1219. // Issue: #285
  1220. if ( document.querySelector( HOME_SLIDE_SELECTOR ).classList.contains( 'present' ) ) {
  1221. // Launch async task
  1222. setTimeout( function () {
  1223. var slides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.stack') ), i;
  1224. for( i in slides ) {
  1225. if( slides[i] ) {
  1226. // Reset stack
  1227. setPreviousVerticalIndex( slides[i], 0 );
  1228. }
  1229. }
  1230. }, 0 );
  1231. }
  1232. }
  1233. // Handle embedded content
  1234. if( slideChanged ) {
  1235. stopEmbeddedContent( previousSlide );
  1236. startEmbeddedContent( currentSlide );
  1237. }
  1238. updateControls();
  1239. updateProgress();
  1240. updateBackground();
  1241. updateParallax();
  1242. updateSlideNumber();
  1243. // Update the URL hash
  1244. writeURL();
  1245. cueAutoSlide();
  1246. }
  1247. /**
  1248. * Syncs the presentation with the current DOM. Useful
  1249. * when new slides or control elements are added or when
  1250. * the configuration has changed.
  1251. */
  1252. function sync() {
  1253. // Subscribe to input
  1254. removeEventListeners();
  1255. addEventListeners();
  1256. // Force a layout to make sure the current config is accounted for
  1257. layout();
  1258. // Reflect the current autoSlide value
  1259. autoSlide = config.autoSlide;
  1260. // Start auto-sliding if it's enabled
  1261. cueAutoSlide();
  1262. // Re-create the slide backgrounds
  1263. createBackgrounds();
  1264. updateControls();
  1265. updateProgress();
  1266. updateBackground( true );
  1267. updateSlideNumber();
  1268. }
  1269. /**
  1270. * Updates one dimension of slides by showing the slide
  1271. * with the specified index.
  1272. *
  1273. * @param {String} selector A CSS selector that will fetch
  1274. * the group of slides we are working with
  1275. * @param {Number} index The index of the slide that should be
  1276. * shown
  1277. *
  1278. * @return {Number} The index of the slide that is now shown,
  1279. * might differ from the passed in index if it was out of
  1280. * bounds.
  1281. */
  1282. function updateSlides( selector, index ) {
  1283. // Select all slides and convert the NodeList result to
  1284. // an array
  1285. var slides = toArray( document.querySelectorAll( selector ) ),
  1286. slidesLength = slides.length;
  1287. if( slidesLength ) {
  1288. // Should the index loop?
  1289. if( config.loop ) {
  1290. index %= slidesLength;
  1291. if( index < 0 ) {
  1292. index = slidesLength + index;
  1293. }
  1294. }
  1295. // Enforce max and minimum index bounds
  1296. index = Math.max( Math.min( index, slidesLength - 1 ), 0 );
  1297. for( var i = 0; i < slidesLength; i++ ) {
  1298. var element = slides[i];
  1299. var reverse = config.rtl && !isVerticalSlide( element );
  1300. element.classList.remove( 'past' );
  1301. element.classList.remove( 'present' );
  1302. element.classList.remove( 'future' );
  1303. // http://www.w3.org/html/wg/drafts/html/master/editing.html#the-hidden-attribute
  1304. element.setAttribute( 'hidden', '' );
  1305. if( i < index ) {
  1306. // Any element previous to index is given the 'past' class
  1307. element.classList.add( reverse ? 'future' : 'past' );
  1308. var pastFragments = toArray( element.querySelectorAll( '.fragment' ) );
  1309. // Show all fragments on prior slides
  1310. while( pastFragments.length ) {
  1311. var pastFragment = pastFragments.pop();
  1312. pastFragment.classList.add( 'visible' );
  1313. pastFragment.classList.remove( 'current-fragment' );
  1314. }
  1315. }
  1316. else if( i > index ) {
  1317. // Any element subsequent to index is given the 'future' class
  1318. element.classList.add( reverse ? 'past' : 'future' );
  1319. var futureFragments = toArray( element.querySelectorAll( '.fragment.visible' ) );
  1320. // No fragments in future slides should be visible ahead of time
  1321. while( futureFragments.length ) {
  1322. var futureFragment = futureFragments.pop();
  1323. futureFragment.classList.remove( 'visible' );
  1324. futureFragment.classList.remove( 'current-fragment' );
  1325. }
  1326. }
  1327. // If this element contains vertical slides
  1328. if( element.querySelector( 'section' ) ) {
  1329. element.classList.add( 'stack' );
  1330. }
  1331. }
  1332. // Mark the current slide as present
  1333. slides[index].classList.add( 'present' );
  1334. slides[index].removeAttribute( 'hidden' );
  1335. // If this slide has a state associated with it, add it
  1336. // onto the current state of the deck
  1337. var slideState = slides[index].getAttribute( 'data-state' );
  1338. if( slideState ) {
  1339. state = state.concat( slideState.split( ' ' ) );
  1340. }
  1341. }
  1342. else {
  1343. // Since there are no slides we can't be anywhere beyond the
  1344. // zeroth index
  1345. index = 0;
  1346. }
  1347. return index;
  1348. }
  1349. /**
  1350. * Optimization method; hide all slides that are far away
  1351. * from the present slide.
  1352. */
  1353. function updateSlidesVisibility() {
  1354. // Select all slides and convert the NodeList result to
  1355. // an array
  1356. var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ),
  1357. horizontalSlidesLength = horizontalSlides.length,
  1358. distanceX,
  1359. distanceY;
  1360. if( horizontalSlidesLength ) {
  1361. // The number of steps away from the present slide that will
  1362. // be visible
  1363. var viewDistance = isOverview() ? 10 : config.viewDistance;
  1364. // Limit view distance on weaker devices
  1365. if( isMobileDevice ) {
  1366. viewDistance = isOverview() ? 6 : 1;
  1367. }
  1368. for( var x = 0; x < horizontalSlidesLength; x++ ) {
  1369. var horizontalSlide = horizontalSlides[x];
  1370. var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ),
  1371. verticalSlidesLength = verticalSlides.length;
  1372. // Loops so that it measures 1 between the first and last slides
  1373. distanceX = Math.abs( ( indexh - x ) % ( horizontalSlidesLength - viewDistance ) ) || 0;
  1374. // Show the horizontal slide if it's within the view distance
  1375. horizontalSlide.style.display = distanceX > viewDistance ? 'none' : 'block';
  1376. if( verticalSlidesLength ) {
  1377. var oy = getPreviousVerticalIndex( horizontalSlide );
  1378. for( var y = 0; y < verticalSlidesLength; y++ ) {
  1379. var verticalSlide = verticalSlides[y];
  1380. distanceY = x === indexh ? Math.abs( indexv - y ) : Math.abs( y - oy );
  1381. verticalSlide.style.display = ( distanceX + distanceY ) > viewDistance ? 'none' : 'block';
  1382. }
  1383. }
  1384. }
  1385. }
  1386. }
  1387. /**
  1388. * Updates the progress bar to reflect the current slide.
  1389. */
  1390. function updateProgress() {
  1391. // Update progress if enabled
  1392. if( config.progress && dom.progress ) {
  1393. var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
  1394. // The number of past and total slides
  1395. var totalCount = document.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length;
  1396. var pastCount = 0;
  1397. // Step through all slides and count the past ones
  1398. mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) {
  1399. var horizontalSlide = horizontalSlides[i];
  1400. var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
  1401. for( var j = 0; j < verticalSlides.length; j++ ) {
  1402. // Stop as soon as we arrive at the present
  1403. if( verticalSlides[j].classList.contains( 'present' ) ) {
  1404. break mainLoop;
  1405. }
  1406. pastCount++;
  1407. }
  1408. // Stop as soon as we arrive at the present
  1409. if( horizontalSlide.classList.contains( 'present' ) ) {
  1410. break;
  1411. }
  1412. // Don't count the wrapping section for vertical slides
  1413. if( horizontalSlide.classList.contains( 'stack' ) === false ) {
  1414. pastCount++;
  1415. }
  1416. }
  1417. dom.progressbar.style.width = ( pastCount / ( totalCount - 1 ) ) * window.innerWidth + 'px';
  1418. }
  1419. }
  1420. /**
  1421. * Updates the slide number div to reflect the current slide.
  1422. */
  1423. function updateSlideNumber() {
  1424. // Update slide number if enabled
  1425. if( config.slideNumber && dom.slideNumber) {
  1426. // Display the number of the page using 'indexh - indexv' format
  1427. var indexString = indexh;
  1428. if( indexv > 0 ) {
  1429. indexString += ' - ' + indexv;
  1430. }
  1431. dom.slideNumber.innerHTML = indexString;
  1432. }
  1433. }
  1434. /**
  1435. * Updates the state of all control/navigation arrows.
  1436. */
  1437. function updateControls() {
  1438. var routes = availableRoutes();
  1439. var fragments = availableFragments();
  1440. // Remove the 'enabled' class from all directions
  1441. dom.controlsLeft.concat( dom.controlsRight )
  1442. .concat( dom.controlsUp )
  1443. .concat( dom.controlsDown )
  1444. .concat( dom.controlsPrev )
  1445. .concat( dom.controlsNext ).forEach( function( node ) {
  1446. node.classList.remove( 'enabled' );
  1447. node.classList.remove( 'fragmented' );
  1448. } );
  1449. // Add the 'enabled' class to the available routes
  1450. if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' ); } );
  1451. if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); } );
  1452. if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); } );
  1453. if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); } );
  1454. // Prev/next buttons
  1455. if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); } );
  1456. if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); } );
  1457. // Highlight fragment directions
  1458. if( currentSlide ) {
  1459. // Always apply fragment decorator to prev/next buttons
  1460. if( fragments.prev ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
  1461. if( fragments.next ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
  1462. // Apply fragment decorators to directional buttons based on
  1463. // what slide axis they are in
  1464. if( isVerticalSlide( currentSlide ) ) {
  1465. if( fragments.prev ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
  1466. if( fragments.next ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
  1467. }
  1468. else {
  1469. if( fragments.prev ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
  1470. if( fragments.next ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } );
  1471. }
  1472. }
  1473. }
  1474. /**
  1475. * Updates the background elements to reflect the current
  1476. * slide.
  1477. *
  1478. * @param {Boolean} includeAll If true, the backgrounds of
  1479. * all vertical slides (not just the present) will be updated.
  1480. */
  1481. function updateBackground( includeAll ) {
  1482. var currentBackground = null;
  1483. // Reverse past/future classes when in RTL mode
  1484. var horizontalPast = config.rtl ? 'future' : 'past',
  1485. horizontalFuture = config.rtl ? 'past' : 'future';
  1486. // Update the classes of all backgrounds to match the
  1487. // states of their slides (past/present/future)
  1488. toArray( dom.background.childNodes ).forEach( function( backgroundh, h ) {
  1489. if( h < indexh ) {
  1490. backgroundh.className = 'slide-background ' + horizontalPast;
  1491. }
  1492. else if ( h > indexh ) {
  1493. backgroundh.className = 'slide-background ' + horizontalFuture;
  1494. }
  1495. else {
  1496. backgroundh.className = 'slide-background present';
  1497. // Store a reference to the current background element
  1498. currentBackground = backgroundh;
  1499. }
  1500. if( includeAll || h === indexh ) {
  1501. toArray( backgroundh.childNodes ).forEach( function( backgroundv, v ) {
  1502. if( v < indexv ) {
  1503. backgroundv.className = 'slide-background past';
  1504. }
  1505. else if ( v > indexv ) {
  1506. backgroundv.className = 'slide-background future';
  1507. }
  1508. else {
  1509. backgroundv.className = 'slide-background present';
  1510. // Only if this is the present horizontal and vertical slide
  1511. if( h === indexh ) currentBackground = backgroundv;
  1512. }
  1513. } );
  1514. }
  1515. } );
  1516. // Don't transition between identical backgrounds. This
  1517. // prevents unwanted flicker.
  1518. if( currentBackground ) {
  1519. var previousBackgroundHash = previousBackground ? previousBackground.getAttribute( 'data-background-hash' ) : null;
  1520. var currentBackgroundHash = currentBackground.getAttribute( 'data-background-hash' );
  1521. if( currentBackgroundHash && currentBackgroundHash === previousBackgroundHash && currentBackground !== previousBackground ) {
  1522. dom.background.classList.add( 'no-transition' );
  1523. }
  1524. previousBackground = currentBackground;
  1525. }
  1526. // Allow the first background to apply without transition
  1527. setTimeout( function() {
  1528. dom.background.classList.remove( 'no-transition' );
  1529. }, 1 );
  1530. }
  1531. /**
  1532. * Updates the position of the parallax background based
  1533. * on the current slide index.
  1534. */
  1535. function updateParallax() {
  1536. if( config.parallaxBackgroundImage ) {
  1537. var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
  1538. verticalSlides = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
  1539. var backgroundSize = dom.background.style.backgroundSize.split( ' ' ),
  1540. backgroundWidth, backgroundHeight;
  1541. if( backgroundSize.length === 1 ) {
  1542. backgroundWidth = backgroundHeight = parseInt( backgroundSize[0], 10 );
  1543. }
  1544. else {
  1545. backgroundWidth = parseInt( backgroundSize[0], 10 );
  1546. backgroundHeight = parseInt( backgroundSize[1], 10 );
  1547. }
  1548. var slideWidth = dom.background.offsetWidth;
  1549. var horizontalSlideCount = horizontalSlides.length;
  1550. var horizontalOffset = -( backgroundWidth - slideWidth ) / ( horizontalSlideCount-1 ) * indexh;
  1551. var slideHeight = dom.background.offsetHeight;
  1552. var verticalSlideCount = verticalSlides.length;
  1553. var verticalOffset = verticalSlideCount > 0 ? -( backgroundHeight - slideHeight ) / ( verticalSlideCount-1 ) * indexv : 0;
  1554. dom.background.style.backgroundPosition = horizontalOffset + 'px ' + verticalOffset + 'px';
  1555. }
  1556. }
  1557. /**
  1558. * Determine what available routes there are for navigation.
  1559. *
  1560. * @return {Object} containing four booleans: left/right/up/down
  1561. */
  1562. function availableRoutes() {
  1563. var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
  1564. verticalSlides = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
  1565. var routes = {
  1566. left: indexh > 0 || config.loop,
  1567. right: indexh < horizontalSlides.length - 1 || config.loop,
  1568. up: indexv > 0,
  1569. down: indexv < verticalSlides.length - 1
  1570. };
  1571. // reverse horizontal controls for rtl
  1572. if( config.rtl ) {
  1573. var left = routes.left;
  1574. routes.left = routes.right;
  1575. routes.right = left;
  1576. }
  1577. return routes;
  1578. }
  1579. /**
  1580. * Returns an object describing the available fragment
  1581. * directions.
  1582. *
  1583. * @return {Object} two boolean properties: prev/next
  1584. */
  1585. function availableFragments() {
  1586. if( currentSlide && config.fragments ) {
  1587. var fragments = currentSlide.querySelectorAll( '.fragment' );
  1588. var hiddenFragments = currentSlide.querySelectorAll( '.fragment:not(.visible)' );
  1589. return {
  1590. prev: fragments.length - hiddenFragments.length > 0,
  1591. next: !!hiddenFragments.length
  1592. };
  1593. }
  1594. else {
  1595. return { prev: false, next: false };
  1596. }
  1597. }
  1598. /**
  1599. * Start playback of any embedded content inside of
  1600. * the targeted slide.
  1601. */
  1602. function startEmbeddedContent( slide ) {
  1603. if( slide && !isSpeakerNotes() ) {
  1604. // HTML5 media elements
  1605. toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
  1606. if( el.hasAttribute( 'data-autoplay' ) ) {
  1607. el.play();
  1608. }
  1609. } );
  1610. // iframe embeds
  1611. toArray( slide.querySelectorAll( 'iframe' ) ).forEach( function( el ) {
  1612. el.contentWindow.postMessage( 'slide:start', '*' );
  1613. });
  1614. // YouTube embeds
  1615. toArray( slide.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) {
  1616. if( el.hasAttribute( 'data-autoplay' ) ) {
  1617. el.contentWindow.postMessage( '{"event":"command","func":"playVideo","args":""}', '*' );
  1618. }
  1619. });
  1620. }
  1621. }
  1622. /**
  1623. * Stop playback of any embedded content inside of
  1624. * the targeted slide.
  1625. */
  1626. function stopEmbeddedContent( slide ) {
  1627. if( slide ) {
  1628. // HTML5 media elements
  1629. toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) {
  1630. if( !el.hasAttribute( 'data-ignore' ) ) {
  1631. el.pause();
  1632. }
  1633. } );
  1634. // iframe embeds
  1635. toArray( slide.querySelectorAll( 'iframe' ) ).forEach( function( el ) {
  1636. el.contentWindow.postMessage( 'slide:stop', '*' );
  1637. });
  1638. // YouTube embeds
  1639. toArray( slide.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) {
  1640. if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) {
  1641. el.contentWindow.postMessage( '{"event":"command","func":"pauseVideo","args":""}', '*' );
  1642. }
  1643. });
  1644. }
  1645. }
  1646. /**
  1647. * Checks if this presentation is running inside of the
  1648. * speaker notes window.
  1649. */
  1650. function isSpeakerNotes() {
  1651. return !!window.location.search.match( /receiver/gi );
  1652. }
  1653. /**
  1654. * Reads the current URL (hash) and navigates accordingly.
  1655. */
  1656. function readURL() {
  1657. var hash = window.location.hash;
  1658. // Attempt to parse the hash as either an index or name
  1659. var bits = hash.slice( 2 ).split( '/' ),
  1660. name = hash.replace( /#|\//gi, '' );
  1661. // If the first bit is invalid and there is a name we can
  1662. // assume that this is a named link
  1663. if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) {
  1664. // Find the slide with the specified name
  1665. var element = document.querySelector( '#' + name );
  1666. if( element ) {
  1667. // Find the position of the named slide and navigate to it
  1668. var indices = Reveal.getIndices( element );
  1669. slide( indices.h, indices.v );
  1670. }
  1671. // If the slide doesn't exist, navigate to the current slide
  1672. else {
  1673. slide( indexh || 0, indexv || 0 );
  1674. }
  1675. }
  1676. else {
  1677. // Read the index components of the hash
  1678. var h = parseInt( bits[0], 10 ) || 0,
  1679. v = parseInt( bits[1], 10 ) || 0;
  1680. if( h !== indexh || v !== indexv ) {
  1681. slide( h, v );
  1682. }
  1683. }
  1684. }
  1685. /**
  1686. * Updates the page URL (hash) to reflect the current
  1687. * state.
  1688. *
  1689. * @param {Number} delay The time in ms to wait before
  1690. * writing the hash
  1691. */
  1692. function writeURL( delay ) {
  1693. if( config.history ) {
  1694. // Make sure there's never more than one timeout running
  1695. clearTimeout( writeURLTimeout );
  1696. // If a delay is specified, timeout this call
  1697. if( typeof delay === 'number' ) {
  1698. writeURLTimeout = setTimeout( writeURL, delay );
  1699. }
  1700. else {
  1701. var url = '/';
  1702. // If the current slide has an ID, use that as a named link
  1703. if( currentSlide && typeof currentSlide.getAttribute( 'id' ) === 'string' ) {
  1704. url = '/' + currentSlide.getAttribute( 'id' );
  1705. }
  1706. // Otherwise use the /h/v index
  1707. else {
  1708. if( indexh > 0 || indexv > 0 ) url += indexh;
  1709. if( indexv > 0 ) url += '/' + indexv;
  1710. }
  1711. window.location.hash = url;
  1712. }
  1713. }
  1714. }
  1715. /**
  1716. * Retrieves the h/v location of the current, or specified,
  1717. * slide.
  1718. *
  1719. * @param {HTMLElement} slide If specified, the returned
  1720. * index will be for this slide rather than the currently
  1721. * active one
  1722. *
  1723. * @return {Object} { h: <int>, v: <int>, f: <int> }
  1724. */
  1725. function getIndices( slide ) {
  1726. // By default, return the current indices
  1727. var h = indexh,
  1728. v = indexv,
  1729. f;
  1730. // If a slide is specified, return the indices of that slide
  1731. if( slide ) {
  1732. var isVertical = isVerticalSlide( slide );
  1733. var slideh = isVertical ? slide.parentNode : slide;
  1734. // Select all horizontal slides
  1735. var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
  1736. // Now that we know which the horizontal slide is, get its index
  1737. h = Math.max( horizontalSlides.indexOf( slideh ), 0 );
  1738. // If this is a vertical slide, grab the vertical index
  1739. if( isVertical ) {
  1740. v = Math.max( toArray( slide.parentNode.querySelectorAll( 'section' ) ).indexOf( slide ), 0 );
  1741. }
  1742. }
  1743. if( !slide && currentSlide ) {
  1744. var hasFragments = currentSlide.querySelectorAll( '.fragment' ).length > 0;
  1745. if( hasFragments ) {
  1746. var visibleFragments = currentSlide.querySelectorAll( '.fragment.visible' );
  1747. f = visibleFragments.length - 1;
  1748. }
  1749. }
  1750. return { h: h, v: v, f: f };
  1751. }
  1752. /**
  1753. * Navigate to the specified slide fragment.
  1754. *
  1755. * @param {Number} index The index of the fragment that
  1756. * should be shown, -1 means all are invisible
  1757. * @param {Number} offset Integer offset to apply to the
  1758. * fragment index
  1759. *
  1760. * @return {Boolean} true if a change was made in any
  1761. * fragments visibility as part of this call
  1762. */
  1763. function navigateFragment( index, offset ) {
  1764. if( currentSlide && config.fragments ) {
  1765. var fragments = sortFragments( currentSlide.querySelectorAll( '.fragment' ) );
  1766. if( fragments.length ) {
  1767. // If no index is specified, find the current
  1768. if( typeof index !== 'number' ) {
  1769. var lastVisibleFragment = sortFragments( currentSlide.querySelectorAll( '.fragment.visible' ) ).pop();
  1770. if( lastVisibleFragment ) {
  1771. index = parseInt( lastVisibleFragment.getAttribute( 'data-fragment-index' ) || 0, 10 );
  1772. }
  1773. else {
  1774. index = -1;
  1775. }
  1776. }
  1777. // If an offset is specified, apply it to the index
  1778. if( typeof offset === 'number' ) {
  1779. index += offset;
  1780. }
  1781. var fragmentsShown = [],
  1782. fragmentsHidden = [];
  1783. toArray( fragments ).forEach( function( element, i ) {
  1784. if( element.hasAttribute( 'data-fragment-index' ) ) {
  1785. i = parseInt( element.getAttribute( 'data-fragment-index' ), 10 );
  1786. }
  1787. // Visible fragments
  1788. if( i <= index ) {
  1789. if( !element.classList.contains( 'visible' ) ) fragmentsShown.push( element );
  1790. element.classList.add( 'visible' );
  1791. element.classList.remove( 'current-fragment' );
  1792. if( i === index ) {
  1793. element.classList.add( 'current-fragment' );
  1794. }
  1795. }
  1796. // Hidden fragments
  1797. else {
  1798. if( element.classList.contains( 'visible' ) ) fragmentsHidden.push( element );
  1799. element.classList.remove( 'visible' );
  1800. element.classList.remove( 'current-fragment' );
  1801. }
  1802. } );
  1803. if( fragmentsHidden.length ) {
  1804. dispatchEvent( 'fragmenthidden', { fragment: fragmentsHidden[0], fragments: fragmentsHidden } );
  1805. }
  1806. if( fragmentsShown.length ) {
  1807. dispatchEvent( 'fragmentshown', { fragment: fragmentsShown[0], fragments: fragmentsShown } );
  1808. }
  1809. updateControls();
  1810. return !!( fragmentsShown.length || fragmentsHidden.length );
  1811. }
  1812. }
  1813. return false;
  1814. }
  1815. /**
  1816. * Navigate to the next slide fragment.
  1817. *
  1818. * @return {Boolean} true if there was a next fragment,
  1819. * false otherwise
  1820. */
  1821. function nextFragment() {
  1822. return navigateFragment( null, 1 );
  1823. }
  1824. /**
  1825. * Navigate to the previous slide fragment.
  1826. *
  1827. * @return {Boolean} true if there was a previous fragment,
  1828. * false otherwise
  1829. */
  1830. function previousFragment() {
  1831. return navigateFragment( null, -1 );
  1832. }
  1833. /**
  1834. * Cues a new automated slide if enabled in the config.
  1835. */
  1836. function cueAutoSlide() {
  1837. cancelAutoSlide();
  1838. if( currentSlide ) {
  1839. var parentAutoSlide = currentSlide.parentNode ? currentSlide.parentNode.getAttribute( 'data-autoslide' ) : null;
  1840. var slideAutoSlide = currentSlide.getAttribute( 'data-autoslide' );
  1841. // Pick value in the following priority order:
  1842. // 1. Current slide's data-autoslide
  1843. // 2. Parent slide's data-autoslide
  1844. // 3. Global autoSlide setting
  1845. if( slideAutoSlide ) {
  1846. autoSlide = parseInt( slideAutoSlide, 10 );
  1847. }
  1848. else if( parentAutoSlide ) {
  1849. autoSlide = parseInt( parentAutoSlide, 10 );
  1850. }
  1851. else {
  1852. autoSlide = config.autoSlide;
  1853. }
  1854. // Cue the next auto-slide if:
  1855. // - There is an autoSlide value
  1856. // - Auto-sliding isn't paused by the user
  1857. // - The presentation isn't paused
  1858. // - The overview isn't active
  1859. // - The presentation isn't over
  1860. if( autoSlide && !autoSlidePaused && !isPaused() && !isOverview() && ( !Reveal.isLastSlide() || config.loop === true ) ) {
  1861. autoSlideTimeout = setTimeout( navigateNext, autoSlide );
  1862. autoSlideStartTime = Date.now();
  1863. }
  1864. if( autoSlidePlayer ) {
  1865. autoSlidePlayer.setPlaying( autoSlideTimeout !== -1 );
  1866. }
  1867. }
  1868. }
  1869. /**
  1870. * Cancels any ongoing request to auto-slide.
  1871. */
  1872. function cancelAutoSlide() {
  1873. clearTimeout( autoSlideTimeout );
  1874. autoSlideTimeout = -1;
  1875. }
  1876. function pauseAutoSlide() {
  1877. autoSlidePaused = true;
  1878. clearTimeout( autoSlideTimeout );
  1879. if( autoSlidePlayer ) {
  1880. autoSlidePlayer.setPlaying( false );
  1881. }
  1882. }
  1883. function resumeAutoSlide() {
  1884. autoSlidePaused = false;
  1885. cueAutoSlide();
  1886. }
  1887. function navigateLeft() {
  1888. // Reverse for RTL
  1889. if( config.rtl ) {
  1890. if( ( isOverview() || nextFragment() === false ) && availableRoutes().left ) {
  1891. slide( indexh + 1 );
  1892. }
  1893. }
  1894. // Normal navigation
  1895. else if( ( isOverview() || previousFragment() === false ) && availableRoutes().left ) {
  1896. slide( indexh - 1 );
  1897. }
  1898. }
  1899. function navigateRight() {
  1900. // Reverse for RTL
  1901. if( config.rtl ) {
  1902. if( ( isOverview() || previousFragment() === false ) && availableRoutes().right ) {
  1903. slide( indexh - 1 );
  1904. }
  1905. }
  1906. // Normal navigation
  1907. else if( ( isOverview() || nextFragment() === false ) && availableRoutes().right ) {
  1908. slide( indexh + 1 );
  1909. }
  1910. }
  1911. function navigateUp() {
  1912. // Prioritize hiding fragments
  1913. if( ( isOverview() || previousFragment() === false ) && availableRoutes().up ) {
  1914. slide( indexh, indexv - 1 );
  1915. }
  1916. }
  1917. function navigateDown() {
  1918. // Prioritize revealing fragments
  1919. if( ( isOverview() || nextFragment() === false ) && availableRoutes().down ) {
  1920. slide( indexh, indexv + 1 );
  1921. }
  1922. }
  1923. /**
  1924. * Navigates backwards, prioritized in the following order:
  1925. * 1) Previous fragment
  1926. * 2) Previous vertical slide
  1927. * 3) Previous horizontal slide
  1928. */
  1929. function navigatePrev() {
  1930. // Prioritize revealing fragments
  1931. if( previousFragment() === false ) {
  1932. if( availableRoutes().up ) {
  1933. navigateUp();
  1934. }
  1935. else {
  1936. // Fetch the previous horizontal slide, if there is one
  1937. var previousSlide = document.querySelector( HORIZONTAL_SLIDES_SELECTOR + '.past:nth-child(' + indexh + ')' );
  1938. if( previousSlide ) {
  1939. var v = ( previousSlide.querySelectorAll( 'section' ).length - 1 ) || undefined;
  1940. var h = indexh - 1;
  1941. slide( h, v );
  1942. }
  1943. }
  1944. }
  1945. }
  1946. /**
  1947. * Same as #navigatePrev() but navigates forwards.
  1948. */
  1949. function navigateNext() {
  1950. // Prioritize revealing fragments
  1951. if( nextFragment() === false ) {
  1952. availableRoutes().down ? navigateDown() : navigateRight();
  1953. }
  1954. // If auto-sliding is enabled we need to cue up
  1955. // another timeout
  1956. cueAutoSlide();
  1957. }
  1958. // --------------------------------------------------------------------//
  1959. // ----------------------------- EVENTS -------------------------------//
  1960. // --------------------------------------------------------------------//
  1961. /**
  1962. * Called by all event handlers that are based on user
  1963. * input.
  1964. */
  1965. function onUserInput( event ) {
  1966. if( config.autoSlideStoppable ) {
  1967. pauseAutoSlide();
  1968. }
  1969. }
  1970. /**
  1971. * Handler for the document level 'keydown' event.
  1972. */
  1973. function onDocumentKeyDown( event ) {
  1974. onUserInput( event );
  1975. // Check if there's a focused element that could be using
  1976. // the keyboard
  1977. var activeElement = document.activeElement;
  1978. var hasFocus = !!( document.activeElement && ( document.activeElement.type || document.activeElement.href || document.activeElement.contentEditable !== 'inherit' ) );
  1979. // Disregard the event if there's a focused element or a
  1980. // keyboard modifier key is present
  1981. if( hasFocus || (event.shiftKey && event.keyCode !== 32) || event.altKey || event.ctrlKey || event.metaKey ) return;
  1982. // While paused only allow "unpausing" keyboard events (b and .)
  1983. if( isPaused() && [66,190,191].indexOf( event.keyCode ) === -1 ) {
  1984. return false;
  1985. }
  1986. var triggered = false;
  1987. // 1. User defined key bindings
  1988. if( typeof config.keyboard === 'object' ) {
  1989. for( var key in config.keyboard ) {
  1990. // Check if this binding matches the pressed key
  1991. if( parseInt( key, 10 ) === event.keyCode ) {
  1992. var value = config.keyboard[ key ];
  1993. // Callback function
  1994. if( typeof value === 'function' ) {
  1995. value.apply( null, [ event ] );
  1996. }
  1997. // String shortcuts to reveal.js API
  1998. else if( typeof value === 'string' && typeof Reveal[ value ] === 'function' ) {
  1999. Reveal[ value ].call();
  2000. }
  2001. triggered = true;
  2002. }
  2003. }
  2004. }
  2005. // 2. System defined key bindings
  2006. if( triggered === false ) {
  2007. // Assume true and try to prove false
  2008. triggered = true;
  2009. switch( event.keyCode ) {
  2010. // p, page up
  2011. case 80: case 33: navigatePrev(); break;
  2012. // n, page down
  2013. case 78: case 34: navigateNext(); break;
  2014. // h, left
  2015. case 72: case 37: navigateLeft(); break;
  2016. // l, right
  2017. case 76: case 39: navigateRight(); break;
  2018. // k, up
  2019. case 75: case 38: navigateUp(); break;
  2020. // j, down
  2021. case 74: case 40: navigateDown(); break;
  2022. // home
  2023. case 36: slide( 0 ); break;
  2024. // end
  2025. case 35: slide( Number.MAX_VALUE ); break;
  2026. // space
  2027. case 32: isOverview() ? deactivateOverview() : event.shiftKey ? navigatePrev() : navigateNext(); break;
  2028. // return
  2029. case 13: isOverview() ? deactivateOverview() : triggered = false; break;
  2030. // b, period, Logitech presenter tools "black screen" button
  2031. case 66: case 190: case 191: togglePause(); break;
  2032. // f
  2033. case 70: enterFullscreen(); break;
  2034. default:
  2035. triggered = false;
  2036. }
  2037. }
  2038. // If the input resulted in a triggered action we should prevent
  2039. // the browsers default behavior
  2040. if( triggered ) {
  2041. event.preventDefault();
  2042. }
  2043. // ESC or O key
  2044. else if ( ( event.keyCode === 27 || event.keyCode === 79 ) && features.transforms3d ) {
  2045. if( dom.preview ) {
  2046. closePreview();
  2047. }
  2048. else {
  2049. toggleOverview();
  2050. }
  2051. event.preventDefault();
  2052. }
  2053. // If auto-sliding is enabled we need to cue up
  2054. // another timeout
  2055. cueAutoSlide();
  2056. }
  2057. /**
  2058. * Handler for the 'touchstart' event, enables support for
  2059. * swipe and pinch gestures.
  2060. */
  2061. function onTouchStart( event ) {
  2062. touch.startX = event.touches[0].clientX;
  2063. touch.startY = event.touches[0].clientY;
  2064. touch.startCount = event.touches.length;
  2065. // If there's two touches we need to memorize the distance
  2066. // between those two points to detect pinching
  2067. if( event.touches.length === 2 && config.overview ) {
  2068. touch.startSpan = distanceBetween( {
  2069. x: event.touches[1].clientX,
  2070. y: event.touches[1].clientY
  2071. }, {
  2072. x: touch.startX,
  2073. y: touch.startY
  2074. } );
  2075. }
  2076. }
  2077. /**
  2078. * Handler for the 'touchmove' event.
  2079. */
  2080. function onTouchMove( event ) {
  2081. // Each touch should only trigger one action
  2082. if( !touch.captured ) {
  2083. onUserInput( event );
  2084. var currentX = event.touches[0].clientX;
  2085. var currentY = event.touches[0].clientY;
  2086. // If the touch started with two points and still has
  2087. // two active touches; test for the pinch gesture
  2088. if( event.touches.length === 2 && touch.startCount === 2 && config.overview ) {
  2089. // The current distance in pixels between the two touch points
  2090. var currentSpan = distanceBetween( {
  2091. x: event.touches[1].clientX,
  2092. y: event.touches[1].clientY
  2093. }, {
  2094. x: touch.startX,
  2095. y: touch.startY
  2096. } );
  2097. // If the span is larger than the desire amount we've got
  2098. // ourselves a pinch
  2099. if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) {
  2100. touch.captured = true;
  2101. if( currentSpan < touch.startSpan ) {
  2102. activateOverview();
  2103. }
  2104. else {
  2105. deactivateOverview();
  2106. }
  2107. }
  2108. event.preventDefault();
  2109. }
  2110. // There was only one touch point, look for a swipe
  2111. else if( event.touches.length === 1 && touch.startCount !== 2 ) {
  2112. var deltaX = currentX - touch.startX,
  2113. deltaY = currentY - touch.startY;
  2114. if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
  2115. touch.captured = true;
  2116. navigateLeft();
  2117. }
  2118. else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
  2119. touch.captured = true;
  2120. navigateRight();
  2121. }
  2122. else if( deltaY > touch.threshold ) {
  2123. touch.captured = true;
  2124. navigateUp();
  2125. }
  2126. else if( deltaY < -touch.threshold ) {
  2127. touch.captured = true;
  2128. navigateDown();
  2129. }
  2130. // If we're embedded, only block touch events if they have
  2131. // triggered an action
  2132. if( config.embedded ) {
  2133. if( touch.captured || isVerticalSlide( currentSlide ) ) {
  2134. event.preventDefault();
  2135. }
  2136. }
  2137. // Not embedded? Block them all to avoid needless tossing
  2138. // around of the viewport in iOS
  2139. else {
  2140. event.preventDefault();
  2141. }
  2142. }
  2143. }
  2144. // There's a bug with swiping on some Android devices unless
  2145. // the default action is always prevented
  2146. else if( navigator.userAgent.match( /android/gi ) ) {
  2147. event.preventDefault();
  2148. }
  2149. }
  2150. /**
  2151. * Handler for the 'touchend' event.
  2152. */
  2153. function onTouchEnd( event ) {
  2154. touch.captured = false;
  2155. }
  2156. /**
  2157. * Convert pointer down to touch start.
  2158. */
  2159. function onPointerDown( event ) {
  2160. if( event.pointerType === event.MSPOINTER_TYPE_TOUCH ) {
  2161. event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
  2162. onTouchStart( event );
  2163. }
  2164. }
  2165. /**
  2166. * Convert pointer move to touch move.
  2167. */
  2168. function onPointerMove( event ) {
  2169. if( event.pointerType === event.MSPOINTER_TYPE_TOUCH ) {
  2170. event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
  2171. onTouchMove( event );
  2172. }
  2173. }
  2174. /**
  2175. * Convert pointer up to touch end.
  2176. */
  2177. function onPointerUp( event ) {
  2178. if( event.pointerType === event.MSPOINTER_TYPE_TOUCH ) {
  2179. event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
  2180. onTouchEnd( event );
  2181. }
  2182. }
  2183. /**
  2184. * Handles mouse wheel scrolling, throttled to avoid skipping
  2185. * multiple slides.
  2186. */
  2187. function onDocumentMouseScroll( event ) {
  2188. if( Date.now() - lastMouseWheelStep > 600 ) {
  2189. lastMouseWheelStep = Date.now();
  2190. var delta = event.detail || -event.wheelDelta;
  2191. if( delta > 0 ) {
  2192. navigateNext();
  2193. }
  2194. else {
  2195. navigatePrev();
  2196. }
  2197. }
  2198. }
  2199. /**
  2200. * Clicking on the progress bar results in a navigation to the
  2201. * closest approximate horizontal slide using this equation:
  2202. *
  2203. * ( clickX / presentationWidth ) * numberOfSlides
  2204. */
  2205. function onProgressClicked( event ) {
  2206. onUserInput( event );
  2207. event.preventDefault();
  2208. var slidesTotal = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length;
  2209. var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal );
  2210. slide( slideIndex );
  2211. }
  2212. /**
  2213. * Event handler for navigation control buttons.
  2214. */
  2215. function onNavigateLeftClicked( event ) { event.preventDefault(); onUserInput(); navigateLeft(); }
  2216. function onNavigateRightClicked( event ) { event.preventDefault(); onUserInput(); navigateRight(); }
  2217. function onNavigateUpClicked( event ) { event.preventDefault(); onUserInput(); navigateUp(); }
  2218. function onNavigateDownClicked( event ) { event.preventDefault(); onUserInput(); navigateDown(); }
  2219. function onNavigatePrevClicked( event ) { event.preventDefault(); onUserInput(); navigatePrev(); }
  2220. function onNavigateNextClicked( event ) { event.preventDefault(); onUserInput(); navigateNext(); }
  2221. /**
  2222. * Handler for the window level 'hashchange' event.
  2223. */
  2224. function onWindowHashChange( event ) {
  2225. readURL();
  2226. }
  2227. /**
  2228. * Handler for the window level 'resize' event.
  2229. */
  2230. function onWindowResize( event ) {
  2231. layout();
  2232. }
  2233. /**
  2234. * Handle for the window level 'visibilitychange' event.
  2235. */
  2236. function onPageVisibilityChange( event ) {
  2237. var isHidden = document.webkitHidden ||
  2238. document.msHidden ||
  2239. document.hidden;
  2240. // If, after clicking a link or similar and we're coming back,
  2241. // focus the document.body to ensure we can use keyboard shortcuts
  2242. if( isHidden === false && document.activeElement !== document.body ) {
  2243. document.activeElement.blur();
  2244. document.body.focus();
  2245. }
  2246. }
  2247. /**
  2248. * Invoked when a slide is and we're in the overview.
  2249. */
  2250. function onOverviewSlideClicked( event ) {
  2251. // TODO There's a bug here where the event listeners are not
  2252. // removed after deactivating the overview.
  2253. if( eventsAreBound && isOverview() ) {
  2254. event.preventDefault();
  2255. var element = event.target;
  2256. while( element && !element.nodeName.match( /section/gi ) ) {
  2257. element = element.parentNode;
  2258. }
  2259. if( element && !element.classList.contains( 'disabled' ) ) {
  2260. deactivateOverview();
  2261. if( element.nodeName.match( /section/gi ) ) {
  2262. var h = parseInt( element.getAttribute( 'data-index-h' ), 10 ),
  2263. v = parseInt( element.getAttribute( 'data-index-v' ), 10 );
  2264. slide( h, v );
  2265. }
  2266. }
  2267. }
  2268. }
  2269. /**
  2270. * Handles clicks on links that are set to preview in the
  2271. * iframe overlay.
  2272. */
  2273. function onPreviewLinkClicked( event ) {
  2274. var url = event.target.getAttribute( 'href' );
  2275. if( url ) {
  2276. openPreview( url );
  2277. event.preventDefault();
  2278. }
  2279. }
  2280. /**
  2281. * Handles click on the auto-sliding controls element.
  2282. */
  2283. function onAutoSlidePlayerClick( event ) {
  2284. // Replay
  2285. if( Reveal.isLastSlide() && config.loop === false ) {
  2286. slide( 0, 0 );
  2287. resumeAutoSlide();
  2288. }
  2289. // Resume
  2290. else if( autoSlidePaused ) {
  2291. resumeAutoSlide();
  2292. }
  2293. // Pause
  2294. else {
  2295. pauseAutoSlide();
  2296. }
  2297. }
  2298. // --------------------------------------------------------------------//
  2299. // ------------------------ PLAYBACK COMPONENT ------------------------//
  2300. // --------------------------------------------------------------------//
  2301. /**
  2302. * Constructor for the playback component, which displays
  2303. * play/pause/progress controls.
  2304. *
  2305. * @param {HTMLElement} container The component will append
  2306. * itself to this
  2307. * @param {Function} progressCheck A method which will be
  2308. * called frequently to get the current progress on a range
  2309. * of 0-1
  2310. */
  2311. function Playback( container, progressCheck ) {
  2312. // Cosmetics
  2313. this.diameter = 50;
  2314. this.thickness = 3;
  2315. // Flags if we are currently playing
  2316. this.playing = false;
  2317. // Current progress on a 0-1 range
  2318. this.progress = 0;
  2319. // Used to loop the animation smoothly
  2320. this.progressOffset = 1;
  2321. this.container = container;
  2322. this.progressCheck = progressCheck;
  2323. this.canvas = document.createElement( 'canvas' );
  2324. this.canvas.className = 'playback';
  2325. this.canvas.width = this.diameter;
  2326. this.canvas.height = this.diameter;
  2327. this.context = this.canvas.getContext( '2d' );
  2328. this.container.appendChild( this.canvas );
  2329. this.render();
  2330. }
  2331. Playback.prototype.setPlaying = function( value ) {
  2332. var wasPlaying = this.playing;
  2333. this.playing = value;
  2334. // Start repainting if we weren't already
  2335. if( !wasPlaying && this.playing ) {
  2336. this.animate();
  2337. }
  2338. else {
  2339. this.render();
  2340. }
  2341. };
  2342. Playback.prototype.animate = function() {
  2343. var progressBefore = this.progress;
  2344. this.progress = this.progressCheck();
  2345. // When we loop, offset the progress so that it eases
  2346. // smoothly rather than immediately resetting
  2347. if( progressBefore > 0.8 && this.progress < 0.2 ) {
  2348. this.progressOffset = this.progress;
  2349. }
  2350. this.render();
  2351. if( this.playing ) {
  2352. features.requestAnimationFrameMethod.call( window, this.animate.bind( this ) );
  2353. }
  2354. };
  2355. /**
  2356. * Renders the current progress and playback state.
  2357. */
  2358. Playback.prototype.render = function() {
  2359. var progress = this.playing ? this.progress : 0,
  2360. radius = ( this.diameter / 2 ) - this.thickness,
  2361. x = this.diameter / 2,
  2362. y = this.diameter / 2,
  2363. iconSize = 14;
  2364. // Ease towards 1
  2365. this.progressOffset += ( 1 - this.progressOffset ) * 0.1;
  2366. var endAngle = ( - Math.PI / 2 ) + ( progress * ( Math.PI * 2 ) );
  2367. var startAngle = ( - Math.PI / 2 ) + ( this.progressOffset * ( Math.PI * 2 ) );
  2368. this.context.save();
  2369. this.context.clearRect( 0, 0, this.diameter, this.diameter );
  2370. // Solid background color
  2371. this.context.beginPath();
  2372. this.context.arc( x, y, radius + 2, 0, Math.PI * 2, false );
  2373. this.context.fillStyle = 'rgba( 0, 0, 0, 0.4 )';
  2374. this.context.fill();
  2375. // Draw progress track
  2376. this.context.beginPath();
  2377. this.context.arc( x, y, radius, 0, Math.PI * 2, false );
  2378. this.context.lineWidth = this.thickness;
  2379. this.context.strokeStyle = '#666';
  2380. this.context.stroke();
  2381. if( this.playing ) {
  2382. // Draw progress on top of track
  2383. this.context.beginPath();
  2384. this.context.arc( x, y, radius, startAngle, endAngle, false );
  2385. this.context.lineWidth = this.thickness;
  2386. this.context.strokeStyle = '#fff';
  2387. this.context.stroke();
  2388. }
  2389. this.context.translate( x - ( iconSize / 2 ), y - ( iconSize / 2 ) );
  2390. // Draw play/pause icons
  2391. if( this.playing ) {
  2392. this.context.fillStyle = '#fff';
  2393. this.context.fillRect( 0, 0, iconSize / 2 - 2, iconSize );
  2394. this.context.fillRect( iconSize / 2 + 2, 0, iconSize / 2 - 2, iconSize );
  2395. }
  2396. else {
  2397. this.context.beginPath();
  2398. this.context.translate( 2, 0 );
  2399. this.context.moveTo( 0, 0 );
  2400. this.context.lineTo( iconSize - 2, iconSize / 2 );
  2401. this.context.lineTo( 0, iconSize );
  2402. this.context.fillStyle = '#fff';
  2403. this.context.fill();
  2404. }
  2405. this.context.restore();
  2406. };
  2407. Playback.prototype.on = function( type, listener ) {
  2408. this.canvas.addEventListener( type, listener, false );
  2409. };
  2410. Playback.prototype.off = function( type, listener ) {
  2411. this.canvas.removeEventListener( type, listener, false );
  2412. };
  2413. Playback.prototype.destroy = function() {
  2414. this.playing = false;
  2415. if( this.canvas.parentNode ) {
  2416. this.container.removeChild( this.canvas );
  2417. }
  2418. };
  2419. // --------------------------------------------------------------------//
  2420. // ------------------------------- API --------------------------------//
  2421. // --------------------------------------------------------------------//
  2422. return {
  2423. initialize: initialize,
  2424. configure: configure,
  2425. sync: sync,
  2426. // Navigation methods
  2427. slide: slide,
  2428. left: navigateLeft,
  2429. right: navigateRight,
  2430. up: navigateUp,
  2431. down: navigateDown,
  2432. prev: navigatePrev,
  2433. next: navigateNext,
  2434. // Fragment methods
  2435. navigateFragment: navigateFragment,
  2436. prevFragment: previousFragment,
  2437. nextFragment: nextFragment,
  2438. // Deprecated aliases
  2439. navigateTo: slide,
  2440. navigateLeft: navigateLeft,
  2441. navigateRight: navigateRight,
  2442. navigateUp: navigateUp,
  2443. navigateDown: navigateDown,
  2444. navigatePrev: navigatePrev,
  2445. navigateNext: navigateNext,
  2446. // Forces an update in slide layout
  2447. layout: layout,
  2448. // Returns an object with the available routes as booleans (left/right/top/bottom)
  2449. availableRoutes: availableRoutes,
  2450. // Returns an object with the available fragments as booleans (prev/next)
  2451. availableFragments: availableFragments,
  2452. // Toggles the overview mode on/off
  2453. toggleOverview: toggleOverview,
  2454. // Toggles the "black screen" mode on/off
  2455. togglePause: togglePause,
  2456. // State checks
  2457. isOverview: isOverview,
  2458. isPaused: isPaused,
  2459. // Adds or removes all internal event listeners (such as keyboard)
  2460. addEventListeners: addEventListeners,
  2461. removeEventListeners: removeEventListeners,
  2462. // Returns the indices of the current, or specified, slide
  2463. getIndices: getIndices,
  2464. // Returns the slide at the specified index, y is optional
  2465. getSlide: function( x, y ) {
  2466. var horizontalSlide = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR )[ x ];
  2467. var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll( 'section' );
  2468. if( typeof y !== 'undefined' ) {
  2469. return verticalSlides ? verticalSlides[ y ] : undefined;
  2470. }
  2471. return horizontalSlide;
  2472. },
  2473. // Returns the previous slide element, may be null
  2474. getPreviousSlide: function() {
  2475. return previousSlide;
  2476. },
  2477. // Returns the current slide element
  2478. getCurrentSlide: function() {
  2479. return currentSlide;
  2480. },
  2481. // Returns the current scale of the presentation content
  2482. getScale: function() {
  2483. return scale;
  2484. },
  2485. // Returns the current configuration object
  2486. getConfig: function() {
  2487. return config;
  2488. },
  2489. // Helper method, retrieves query string as a key/value hash
  2490. getQueryHash: function() {
  2491. var query = {};
  2492. location.search.replace( /[A-Z0-9]+?=(\w*)/gi, function(a) {
  2493. query[ a.split( '=' ).shift() ] = a.split( '=' ).pop();
  2494. } );
  2495. // Basic deserialization
  2496. for( var i in query ) {
  2497. var value = query[ i ];
  2498. if( value === 'null' ) query[ i ] = null;
  2499. else if( value === 'true' ) query[ i ] = true;
  2500. else if( value === 'false' ) query[ i ] = false;
  2501. else if( !isNaN( parseFloat( value ) ) ) query[ i ] = parseFloat( value );
  2502. }
  2503. return query;
  2504. },
  2505. // Returns true if we're currently on the first slide
  2506. isFirstSlide: function() {
  2507. return document.querySelector( SLIDES_SELECTOR + '.past' ) == null ? true : false;
  2508. },
  2509. // Returns true if we're currently on the last slide
  2510. isLastSlide: function() {
  2511. if( currentSlide ) {
  2512. // Does this slide has next a sibling?
  2513. if( currentSlide.nextElementSibling ) return false;
  2514. // If it's vertical, does its parent have a next sibling?
  2515. if( isVerticalSlide( currentSlide ) && currentSlide.parentNode.nextElementSibling ) return false;
  2516. return true;
  2517. }
  2518. return false;
  2519. },
  2520. // Checks if reveal.js has been loaded and is ready for use
  2521. isReady: function() {
  2522. return loaded;
  2523. },
  2524. // Forward event binding to the reveal DOM element
  2525. addEventListener: function( type, listener, useCapture ) {
  2526. if( 'addEventListener' in window ) {
  2527. ( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture );
  2528. }
  2529. },
  2530. removeEventListener: function( type, listener, useCapture ) {
  2531. if( 'addEventListener' in window ) {
  2532. ( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture );
  2533. }
  2534. }
  2535. };
  2536. })();