3 * http://lab.hakim.se/reveal-js
6 * Copyright (C) 2011-2012 Hakim El Hattab, http://hakim.se
8 var Reveal = (function(){
12 var SLIDES_SELECTOR = '.reveal .slides section',
13 HORIZONTAL_SLIDES_SELECTOR = '.reveal .slides>section',
14 VERTICAL_SLIDES_SELECTOR = '.reveal .slides>section.present>section',
16 // Configurations defaults, can be overridden at initialization time
18 // Display controls in the bottom right corner
21 // Display a presentation progress bar
24 // Push each slide change to the browser history
27 // Enable keyboard shortcuts for navigation
30 // Enable the slide overview mode
33 // Vertical centering of slides
36 // Loop the presentation
39 // Experimental support for RTL
42 // Number of milliseconds between automatically proceeding to the
43 // next slide, disabled when set to 0, this value can be overwritten
44 // by using a data-autoslide attribute on your slides
47 // Enable slide navigation via mouse wheel
50 // Apply a 3D roll to links on hover
53 // Transition style (see /css/theme)
57 transition: 'default', // default/cube/page/concave/zoom/linear/none
59 // Script dependencies to load
63 // Stores if the next slide should be shown automatically
64 // after n milliseconds
65 autoSlide = config.autoSlide,
67 // The horizontal and verical index of the currently active slide
71 // The previous and current slide HTML elements
75 // Slides may hold a data-state attribute which we pick up and apply
76 // as a class to the body. This list contains the combined state of
77 // all current slides.
80 // Cached references to DOM elements
83 // Detect support for CSS 3D transforms
84 supports3DTransforms = 'WebkitPerspective' in document.body.style ||
85 'MozPerspective' in document.body.style ||
86 'msPerspective' in document.body.style ||
87 'OPerspective' in document.body.style ||
88 'perspective' in document.body.style,
90 supports2DTransforms = 'WebkitTransform' in document.body.style ||
91 'MozTransform' in document.body.style ||
92 'msTransform' in document.body.style ||
93 'OTransform' in document.body.style ||
94 'transform' in document.body.style,
96 // Throttles mouse wheel navigation
97 mouseWheelTimeout = 0,
99 // An interval used to automatically move on to the next slide
100 autoSlideTimeout = 0,
102 // Delays updates to the URL due to a Chrome thumbnailer bug
105 // Holds information about the currently ongoing touch input
116 * Starts up the presentation if the client is capable.
118 function initialize( options ) {
119 if( ( !supports2DTransforms && !supports3DTransforms ) ) {
120 document.body.setAttribute( 'class', 'no-transforms' );
122 // If the browser doesn't support core features we won't be
123 // using JavaScript to control the presentation
127 // Force a layout when the whole page, incl fonts, has loaded
128 window.addEventListener( 'load', layout, false );
130 // Copy options over to our config object
131 extend( config, options );
133 // Hide the address bar in mobile browsers
136 // Loads the dependencies and continues to #start() once done
142 * Finds and stores references to DOM elements which are
143 * required by the presentation. If a required element is
144 * not found, it is created.
146 function setupDOM() {
147 // Cache references to key DOM elements
148 dom.theme = document.querySelector( '#theme' );
149 dom.wrapper = document.querySelector( '.reveal' );
150 dom.slides = document.querySelector( '.reveal .slides' );
153 if( !dom.wrapper.querySelector( '.progress' ) && config.progress ) {
154 var progressElement = document.createElement( 'div' );
155 progressElement.classList.add( 'progress' );
156 progressElement.innerHTML = '<span></span>';
157 dom.wrapper.appendChild( progressElement );
161 if( !dom.wrapper.querySelector( '.controls' ) && config.controls ) {
162 var controlsElement = document.createElement( 'aside' );
163 controlsElement.classList.add( 'controls' );
164 controlsElement.innerHTML = '<div class="navigate-left"></div>' +
165 '<div class="navigate-right"></div>' +
166 '<div class="navigate-up"></div>' +
167 '<div class="navigate-down"></div>';
168 dom.wrapper.appendChild( controlsElement );
171 // Presentation background element
172 if( !dom.wrapper.querySelector( '.state-background' ) ) {
173 var backgroundElement = document.createElement( 'div' );
174 backgroundElement.classList.add( 'state-background' );
175 dom.wrapper.appendChild( backgroundElement );
178 // Overlay graphic which is displayed during the paused mode
179 if( !dom.wrapper.querySelector( '.pause-overlay' ) ) {
180 var pausedElement = document.createElement( 'div' );
181 pausedElement.classList.add( 'pause-overlay' );
182 dom.wrapper.appendChild( pausedElement );
185 // Cache references to elements
186 dom.progress = document.querySelector( '.reveal .progress' );
187 dom.progressbar = document.querySelector( '.reveal .progress span' );
189 if ( config.controls ) {
190 dom.controls = document.querySelector( '.reveal .controls' );
192 // There can be multiple instances of controls throughout the page
193 dom.controlsLeft = toArray( document.querySelectorAll( '.navigate-left' ) );
194 dom.controlsRight = toArray( document.querySelectorAll( '.navigate-right' ) );
195 dom.controlsUp = toArray( document.querySelectorAll( '.navigate-up' ) );
196 dom.controlsDown = toArray( document.querySelectorAll( '.navigate-down' ) );
197 dom.controlsPrev = toArray( document.querySelectorAll( '.navigate-prev' ) );
198 dom.controlsNext = toArray( document.querySelectorAll( '.navigate-next' ) );
203 * Hides the address bar if we're on a mobile device.
205 function hideAddressBar() {
206 if( navigator.userAgent.match( /(iphone|ipod)/i ) ) {
207 // Give the page some scrollable overflow
208 document.documentElement.style.overflow = 'scroll';
209 document.body.style.height = '120%';
211 // Events that should trigger the address bar to hide
212 window.addEventListener( 'load', removeAddressBar, false );
213 window.addEventListener( 'orientationchange', removeAddressBar, false );
218 * Loads the dependencies of reveal.js. Dependencies are
219 * defined via the configuration option 'dependencies'
220 * and will be loaded prior to starting/binding reveal.js.
221 * Some dependencies may have an 'async' flag, if so they
222 * will load after reveal.js has been started up.
228 for( var i = 0, len = config.dependencies.length; i < len; i++ ) {
229 var s = config.dependencies[i];
231 // Load if there's no condition or the condition is truthy
232 if( !s.condition || s.condition() ) {
234 scriptsAsync.push( s.src );
237 scripts.push( s.src );
240 // Extension may contain callback functions
241 if( typeof s.callback === 'function' ) {
242 head.ready( s.src.match( /([\w\d_\-]*)\.?js$|[^\\\/]*$/i )[0], s.callback );
247 // Called once synchronous scritps finish loading
249 if( scriptsAsync.length ) {
250 // Load asynchronous scripts
251 head.js.apply( null, scriptsAsync );
257 if( scripts.length ) {
258 head.ready( proceed );
260 // Load synchronous scripts
261 head.js.apply( null, scripts );
269 * Starts up reveal.js by binding input events and navigating
270 * to the current URL deeplink if there is one.
273 // Make sure we've got all the DOM elements we need
276 // Subscribe to input
279 // Updates the presentation to match the current configuration values
282 // Force an initial layout, will thereafter be invoked as the window
286 // Read the initial hash
289 // Start auto-sliding if it's enabled
292 // Notify listeners that the presentation is ready but use a 1ms
293 // timeout to ensure it's not fired synchronously after #initialize()
294 setTimeout( function() {
295 dispatchEvent( 'ready', {
298 'currentSlide': currentSlide
304 * Applies the configuration settings from the config object.
306 function configure() {
307 if( supports3DTransforms === false ) {
308 config.transition = 'linear';
311 if( config.controls && dom.controls ) {
312 dom.controls.style.display = 'block';
315 if( config.progress && dom.progress ) {
316 dom.progress.style.display = 'block';
319 if( config.transition !== 'default' ) {
320 dom.wrapper.classList.add( config.transition );
324 dom.wrapper.classList.add( 'rtl' );
327 if( config.center ) {
328 dom.wrapper.classList.add( 'center' );
331 if( config.mouseWheel ) {
332 document.addEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
333 document.addEventListener( 'mousewheel', onDocumentMouseScroll, false );
337 if( config.rollingLinks ) {
341 // Load the theme in the config, if it's not already loaded
342 if( config.theme && dom.theme ) {
343 var themeURL = dom.theme.getAttribute( 'href' );
344 var themeFinder = /[^\/]*?(?=\.css)/;
345 var themeName = themeURL.match(themeFinder)[0];
347 if( config.theme !== themeName ) {
348 themeURL = themeURL.replace(themeFinder, config.theme);
349 dom.theme.setAttribute( 'href', themeURL );
355 * Binds all event listeners.
357 function addEventListeners() {
358 document.addEventListener( 'touchstart', onDocumentTouchStart, false );
359 document.addEventListener( 'touchmove', onDocumentTouchMove, false );
360 document.addEventListener( 'touchend', onDocumentTouchEnd, false );
361 window.addEventListener( 'hashchange', onWindowHashChange, false );
362 window.addEventListener( 'resize', onWindowResize, false );
364 if( config.keyboard ) {
365 document.addEventListener( 'keydown', onDocumentKeyDown, false );
368 if ( config.progress && dom.progress ) {
369 dom.progress.addEventListener( 'click', preventAndForward( onProgressClick ), false );
372 if ( config.controls && dom.controls ) {
373 var actionEvent = 'ontouchstart' in window ? 'touchstart' : 'click';
374 dom.controlsLeft.forEach( function( el ) { el.addEventListener( actionEvent, preventAndForward( navigateLeft ), false ); } );
375 dom.controlsRight.forEach( function( el ) { el.addEventListener( actionEvent, preventAndForward( navigateRight ), false ); } );
376 dom.controlsUp.forEach( function( el ) { el.addEventListener( actionEvent, preventAndForward( navigateUp ), false ); } );
377 dom.controlsDown.forEach( function( el ) { el.addEventListener( actionEvent, preventAndForward( navigateDown ), false ); } );
378 dom.controlsPrev.forEach( function( el ) { el.addEventListener( actionEvent, preventAndForward( navigatePrev ), false ); } );
379 dom.controlsNext.forEach( function( el ) { el.addEventListener( actionEvent, preventAndForward( navigateNext ), false ); } );
384 * Unbinds all event listeners.
386 function removeEventListeners() {
387 document.removeEventListener( 'keydown', onDocumentKeyDown, false );
388 document.removeEventListener( 'touchstart', onDocumentTouchStart, false );
389 document.removeEventListener( 'touchmove', onDocumentTouchMove, false );
390 document.removeEventListener( 'touchend', onDocumentTouchEnd, false );
391 window.removeEventListener( 'hashchange', onWindowHashChange, false );
392 window.removeEventListener( 'resize', onWindowResize, false );
394 if ( config.progress && dom.progress ) {
395 dom.progress.removeEventListener( 'click', preventAndForward( onProgressClick ), false );
398 if ( config.controls && dom.controls ) {
399 var actionEvent = 'ontouchstart' in window ? 'touchstart' : 'click';
400 dom.controlsLeft.forEach( function( el ) { el.removeEventListener( actionEvent, preventAndForward( navigateLeft ), false ); } );
401 dom.controlsRight.forEach( function( el ) { el.removeEventListener( actionEvent, preventAndForward( navigateRight ), false ); } );
402 dom.controlsUp.forEach( function( el ) { el.removeEventListener( actionEvent, preventAndForward( navigateUp ), false ); } );
403 dom.controlsDown.forEach( function( el ) { el.removeEventListener( actionEvent, preventAndForward( navigateDown ), false ); } );
404 dom.controlsPrev.forEach( function( el ) { el.removeEventListener( actionEvent, preventAndForward( navigatePrev ), false ); } );
405 dom.controlsNext.forEach( function( el ) { el.removeEventListener( actionEvent, preventAndForward( navigateNext ), false ); } );
410 * Extend object a with the properties of object b.
411 * If there's a conflict, object b takes precedence.
413 function extend( a, b ) {
420 * Converts the target object to an array.
422 function toArray( o ) {
423 return Array.prototype.slice.call( o );
426 function each( targets, method, args ) {
427 targets.forEach( function( el ) {
428 el[method].apply( el, args );
433 * Measures the distance in pixels between point a
436 * @param {Object} a point with x/y properties
437 * @param {Object} b point with x/y properties
439 function distanceBetween( a, b ) {
443 return Math.sqrt( dx*dx + dy*dy );
447 * Prevents an events defaults behavior calls the
448 * specified delegate.
450 * @param {Function} delegate The method to call
451 * after the wrapper has been executed
453 function preventAndForward( delegate ) {
454 return function( event ) {
455 event.preventDefault();
456 delegate.call( null, event );
461 * Causes the address bar to hide on mobile devices,
462 * more vertical space ftw.
464 function removeAddressBar() {
465 setTimeout( function() {
466 window.scrollTo( 0, 1 );
471 * Dispatches an event of the specified type from the
472 * reveal DOM element.
474 function dispatchEvent( type, properties ) {
475 var event = document.createEvent( "HTMLEvents", 1, 2 );
476 event.initEvent( type, true, true );
477 extend( event, properties );
478 dom.wrapper.dispatchEvent( event );
482 * Wrap all links in 3D goodness.
485 if( supports3DTransforms && !( 'msPerspective' in document.body.style ) ) {
486 var nodes = document.querySelectorAll( SLIDES_SELECTOR + ' a:not(.image)' );
488 for( var i = 0, len = nodes.length; i < len; i++ ) {
491 if( node.textContent && !node.querySelector( 'img' ) && ( !node.className || !node.classList.contains( node, 'roll' ) ) ) {
492 node.classList.add( 'roll' );
493 node.innerHTML = '<span data-title="'+ node.text +'">' + node.innerHTML + '</span>';
500 * Applies JavaScript-controlled layout rules to the
505 if( config.center ) {
507 // Select all slides, vertical and horizontal
508 var slides = toArray( document.querySelectorAll( SLIDES_SELECTOR ) );
510 // Determine the minimum top offset for slides
511 var minTop = -dom.wrapper.offsetHeight / 2;
513 for( var i = 0, len = slides.length; i < len; i++ ) {
514 var slide = slides[ i ];
516 // Don't bother update invisible slides
517 if( slide.style.display === 'none' ) {
521 // Vertical stacks are not centered since their section
523 if( slide.classList.contains( 'stack' ) ) {
527 slide.style.top = Math.max( - ( slide.offsetHeight / 2 ) - 20, minTop ) + 'px';
536 * Stores the vertical index of a stack so that the same
537 * vertical slide can be selected when navigating to and
540 * @param {HTMLElement} stack The vertical stack element
541 * @param {int} v Index to memorize
543 function setPreviousVerticalIndex( stack, v ) {
545 stack.setAttribute( 'data-previous-indexv', v || 0 );
550 * Retrieves the vertical index which was stored using
551 * #setPreviousVerticalIndex() or 0 if no previous index
554 * @param {HTMLElement} stack The vertical stack element
556 function getPreviousVerticalIndex( stack ) {
557 if( stack && stack.classList.contains( 'stack' ) ) {
558 return parseInt( stack.getAttribute( 'data-previous-indexv' ) || 0, 10 );
565 * Displays the overview of slides (quick nav) by
566 * scaling down and arranging all slide elements.
568 * Experimental feature, might be dropped if perf
571 function activateOverview() {
573 // Only proceed if enabled in config
574 if( config.overview ) {
576 dom.wrapper.classList.add( 'overview' );
578 var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
580 for( var i = 0, len1 = horizontalSlides.length; i < len1; i++ ) {
581 var hslide = horizontalSlides[i],
582 htransform = 'translateZ(-2500px) translate(' + ( ( i - indexh ) * 105 ) + '%, 0%)';
584 hslide.setAttribute( 'data-index-h', i );
585 hslide.style.display = 'block';
586 hslide.style.WebkitTransform = htransform;
587 hslide.style.MozTransform = htransform;
588 hslide.style.msTransform = htransform;
589 hslide.style.OTransform = htransform;
590 hslide.style.transform = htransform;
592 if( hslide.classList.contains( 'stack' ) ) {
594 var verticalSlides = hslide.querySelectorAll( 'section' );
596 for( var j = 0, len2 = verticalSlides.length; j < len2; j++ ) {
597 var verticalIndex = i === indexh ? indexv : getPreviousVerticalIndex( hslide );
599 var vslide = verticalSlides[j],
600 vtransform = 'translate(0%, ' + ( ( j - verticalIndex ) * 105 ) + '%)';
602 vslide.setAttribute( 'data-index-h', i );
603 vslide.setAttribute( 'data-index-v', j );
604 vslide.style.display = 'block';
605 vslide.style.WebkitTransform = vtransform;
606 vslide.style.MozTransform = vtransform;
607 vslide.style.msTransform = vtransform;
608 vslide.style.OTransform = vtransform;
609 vslide.style.transform = vtransform;
611 // Navigate to this slide on click
612 vslide.addEventListener( 'click', onOverviewSlideClicked, true );
618 // Navigate to this slide on click
619 hslide.addEventListener( 'click', onOverviewSlideClicked, true );
631 * Exits the slide overview and enters the currently
634 function deactivateOverview() {
636 // Only proceed if enabled in config
637 if( config.overview ) {
639 dom.wrapper.classList.remove( 'overview' );
642 var slides = toArray( document.querySelectorAll( SLIDES_SELECTOR ) );
644 for( var i = 0, len = slides.length; i < len; i++ ) {
645 var element = slides[i];
647 // Resets all transforms to use the external styles
648 element.style.WebkitTransform = '';
649 element.style.MozTransform = '';
650 element.style.msTransform = '';
651 element.style.OTransform = '';
652 element.style.transform = '';
654 element.removeEventListener( 'click', onOverviewSlideClicked );
657 slide( indexh, indexv );
663 * Toggles the slide overview mode on and off.
665 * @param {Boolean} override Optional flag which overrides the
666 * toggle logic and forcibly sets the desired state. True means
667 * overview is open, false means it's closed.
669 function toggleOverview( override ) {
670 if( typeof override === 'boolean' ) {
671 override ? activateOverview() : deactivateOverview();
674 isOverviewActive() ? deactivateOverview() : activateOverview();
679 * Checks if the overview is currently active.
681 * @return {Boolean} true if the overview is active,
684 function isOverviewActive() {
685 return dom.wrapper.classList.contains( 'overview' );
689 * Handling the fullscreen functionality via the fullscreen API
691 * @see http://fullscreen.spec.whatwg.org/
692 * @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode
694 function enterFullscreen() {
695 var element = document.body;
697 // Check which implementation is available
698 var requestMethod = element.requestFullScreen ||
699 element.webkitRequestFullScreen ||
700 element.mozRequestFullScreen ||
701 element.msRequestFullScreen;
703 if( requestMethod ) {
704 requestMethod.apply( element );
709 * Enters the paused mode which fades everything on screen to
713 dom.wrapper.classList.add( 'paused' );
717 * Exits from the paused mode.
720 dom.wrapper.classList.remove( 'paused' );
724 * Toggles the paused mode on and off.
726 function togglePause() {
736 * Checks if we are currently in the paused mode.
738 function isPaused() {
739 return dom.wrapper.classList.contains( 'paused' );
743 * Steps from the current point in the presentation to the
744 * slide which matches the specified horizontal and vertical
747 * @param {int} h Horizontal index of the target slide
748 * @param {int} v Vertical index of the target slide
749 * @param {int} f Optional index of a fragment within the
750 * target slide to activate
752 function slide( h, v, f ) {
753 // Remember where we were at before
754 previousSlide = currentSlide;
756 // Query all horizontal slides in the deck
757 var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
759 // If no vertical index is specified and the upcoming slide is a
760 // stack, resume at its previous vertical index
761 if( v === undefined ) {
762 v = getPreviousVerticalIndex( horizontalSlides[ h ] );
765 // If we were on a vertical stack, remember what vertical index
766 // it was on so we can resume at the same position when returning
767 if( previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains( 'stack' ) ) {
768 setPreviousVerticalIndex( previousSlide.parentNode, indexv );
771 // Remember the state before this slide
772 var stateBefore = state.concat();
774 // Reset the state array
777 var indexhBefore = indexh,
778 indexvBefore = indexv;
780 // Activate and transition to the new slide
781 indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h );
782 indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v );
786 // Apply the new state
787 stateLoop: for( var i = 0, len = state.length; i < len; i++ ) {
788 // Check if this state existed on the previous slide. If it
789 // did, we will avoid adding it repeatedly
790 for( var j = 0; j < stateBefore.length; j++ ) {
791 if( stateBefore[j] === state[i] ) {
792 stateBefore.splice( j, 1 );
797 document.documentElement.classList.add( state[i] );
799 // Dispatch custom event matching the state's name
800 dispatchEvent( state[i] );
803 // Clean up the remaints of the previous state
804 while( stateBefore.length ) {
805 document.documentElement.classList.remove( stateBefore.pop() );
808 // If the overview is active, re-activate it to update positions
809 if( isOverviewActive() ) {
813 // Update the URL hash after a delay since updating it mid-transition
814 // is likely to cause visual lag
817 // Find the current horizontal slide and any possible vertical slides
819 var currentHorizontalSlide = horizontalSlides[ indexh ],
820 currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' );
822 // Store references to the previous and current slides
823 currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide;
826 // Show fragment, if specified
827 if( ( indexh !== indexhBefore || indexv !== indexvBefore ) && f ) {
828 var fragments = currentSlide.querySelectorAll( '.fragment' );
830 toArray( fragments ).forEach( function( fragment, indexf ) {
832 fragment.classList.add( 'visible' );
835 fragment.classList.remove( 'visible' );
840 // Dispatch an event if the slide changed
841 if( indexh !== indexhBefore || indexv !== indexvBefore ) {
842 dispatchEvent( 'slidechanged', {
845 'previousSlide': previousSlide,
846 'currentSlide': currentSlide
850 // Ensure that the previous slide is never the same as the current
851 previousSlide = null;
854 // Solves an edge case where the previous slide maintains the
855 // 'present' class when navigating between adjacent vertical
857 if( previousSlide ) {
858 previousSlide.classList.remove( 'present' );
866 * Updates one dimension of slides by showing the slide
867 * with the specified index.
869 * @param {String} selector A CSS selector that will fetch
870 * the group of slides we are working with
871 * @param {Number} index The index of the slide that should be
874 * @return {Number} The index of the slide that is now shown,
875 * might differ from the passed in index if it was out of
878 function updateSlides( selector, index ) {
879 // Select all slides and convert the NodeList result to
881 var slides = toArray( document.querySelectorAll( selector ) ),
882 slidesLength = slides.length;
886 // Should the index loop?
888 index %= slidesLength;
891 index = slidesLength + index;
895 // Enforce max and minimum index bounds
896 index = Math.max( Math.min( index, slidesLength - 1 ), 0 );
898 for( var i = 0; i < slidesLength; i++ ) {
899 var element = slides[i];
901 // Optimization; hide all slides that are three or more steps
902 // away from the present slide
903 if( isOverviewActive() === false ) {
904 // The distance loops so that it measures 1 between the first
906 var distance = Math.abs( ( index - i ) % ( slidesLength - 3 ) ) || 0;
908 element.style.display = distance > 3 ? 'none' : 'block';
911 slides[i].classList.remove( 'past' );
912 slides[i].classList.remove( 'present' );
913 slides[i].classList.remove( 'future' );
916 // Any element previous to index is given the 'past' class
917 slides[i].classList.add( 'past' );
919 else if( i > index ) {
920 // Any element subsequent to index is given the 'future' class
921 slides[i].classList.add( 'future' );
924 // If this element contains vertical slides
925 if( element.querySelector( 'section' ) ) {
926 slides[i].classList.add( 'stack' );
930 // Mark the current slide as present
931 slides[index].classList.add( 'present' );
933 // If this slide has a state associated with it, add it
934 // onto the current state of the deck
935 var slideState = slides[index].getAttribute( 'data-state' );
937 state = state.concat( slideState.split( ' ' ) );
940 // If this slide has a data-autoslide attribtue associated use this as
941 // autoSlide value otherwise use the global configured time
942 var slideAutoSlide = slides[index].getAttribute( 'data-autoslide' );
943 if( slideAutoSlide ) {
944 autoSlide = parseInt( slideAutoSlide, 10 );
946 autoSlide = config.autoSlide;
951 // Since there are no slides we can't be anywhere beyond the
961 * Updates the progress bar to reflect the current slide.
963 function updateProgress() {
964 // Update progress if enabled
965 if( config.progress && dom.progress ) {
967 var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
969 // The number of past and total slides
970 var totalCount = document.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length;
973 // Step through all slides and count the past ones
974 mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) {
976 var horizontalSlide = horizontalSlides[i];
977 var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
979 for( var j = 0; j < verticalSlides.length; j++ ) {
981 // Stop as soon as we arrive at the present
982 if( verticalSlides[j].classList.contains( 'present' ) ) {
990 // Stop as soon as we arrive at the present
991 if( horizontalSlide.classList.contains( 'present' ) ) {
995 // Don't count the wrapping section for vertical slides
996 if( horizontalSlide.classList.contains( 'stack' ) === false ) {
1002 dom.progressbar.style.width = ( pastCount / ( totalCount - 1 ) ) * window.innerWidth + 'px';
1008 * Updates the state of all control/navigation arrows.
1010 function updateControls() {
1011 if ( config.controls && dom.controls ) {
1013 var routes = availableRoutes();
1015 // Remove the 'enabled' class from all directions
1016 dom.controlsLeft.concat( dom.controlsRight )
1017 .concat( dom.controlsUp )
1018 .concat( dom.controlsDown )
1019 .concat( dom.controlsPrev )
1020 .concat( dom.controlsNext ).forEach( function( node ) {
1021 node.classList.remove( 'enabled' );
1024 // Add the 'enabled' class to the available routes
1025 if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1026 if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1027 if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1028 if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1030 // Prev/next buttons
1031 if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1032 if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1038 * Determine what available routes there are for navigation.
1040 * @return {Object} containing four booleans: left/right/up/down
1042 function availableRoutes() {
1043 var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
1044 verticalSlides = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
1048 right: indexh < horizontalSlides.length - 1,
1050 down: indexv < verticalSlides.length - 1
1055 * Reads the current URL (hash) and navigates accordingly.
1057 function readURL() {
1058 var hash = window.location.hash;
1060 // Attempt to parse the hash as either an index or name
1061 var bits = hash.slice( 2 ).split( '/' ),
1062 name = hash.replace( /#|\//gi, '' );
1064 // If the first bit is invalid and there is a name we can
1065 // assume that this is a named link
1066 if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) {
1067 // Find the slide with the specified name
1068 var element = document.querySelector( '#' + name );
1071 // Find the position of the named slide and navigate to it
1072 var indices = Reveal.getIndices( element );
1073 slide( indices.h, indices.v );
1075 // If the slide doesn't exist, navigate to the current slide
1077 slide( indexh, indexv );
1081 // Read the index components of the hash
1082 var h = parseInt( bits[0], 10 ) || 0,
1083 v = parseInt( bits[1], 10 ) || 0;
1090 * Updates the page URL (hash) to reflect the current
1093 * @param {Number} delay The time in ms to wait before
1096 function writeURL( delay ) {
1097 if( config.history ) {
1099 // Make sure there's never more than one timeout running
1100 clearTimeout( writeURLTimeout );
1102 // If a delay is specified, timeout this call
1103 if( typeof delay === 'number' ) {
1104 writeURLTimeout = setTimeout( writeURL, delay );
1109 // If the current slide has an ID, use that as a named link
1110 if( currentSlide && typeof currentSlide.getAttribute( 'id' ) === 'string' ) {
1111 url = '/' + currentSlide.getAttribute( 'id' );
1113 // Otherwise use the /h/v index
1115 if( indexh > 0 || indexv > 0 ) url += indexh;
1116 if( indexv > 0 ) url += '/' + indexv;
1119 window.location.hash = url;
1125 * Retrieves the h/v location of the current, or specified,
1128 * @param {HTMLElement} slide If specified, the returned
1129 * index will be for this slide rather than the currently
1132 * @return {Object} { h: <int>, v: <int> }
1134 function getIndices( slide ) {
1135 // By default, return the current indices
1139 // If a slide is specified, return the indices of that slide
1141 var isVertical = !!slide.parentNode.nodeName.match( /section/gi );
1142 var slideh = isVertical ? slide.parentNode : slide;
1144 // Select all horizontal slides
1145 var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
1147 // Now that we know which the horizontal slide is, get its index
1148 h = Math.max( horizontalSlides.indexOf( slideh ), 0 );
1150 // If this is a vertical slide, grab the vertical index
1152 v = Math.max( toArray( slide.parentNode.children ).indexOf( slide ), 0 );
1156 return { h: h, v: v };
1160 * Navigate to the next slide fragment.
1162 * @return {Boolean} true if there was a next fragment,
1165 function nextFragment() {
1167 if( document.querySelector( VERTICAL_SLIDES_SELECTOR + '.present' ) ) {
1168 var verticalFragments = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR + '.present .fragment:not(.visible)' );
1169 if( verticalFragments.length ) {
1170 verticalFragments[0].classList.add( 'visible' );
1172 // Notify subscribers of the change
1173 dispatchEvent( 'fragmentshown', { fragment: verticalFragments[0] } );
1177 // Horizontal slides:
1179 var horizontalFragments = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.present .fragment:not(.visible)' );
1180 if( horizontalFragments.length ) {
1181 horizontalFragments[0].classList.add( 'visible' );
1183 // Notify subscribers of the change
1184 dispatchEvent( 'fragmentshown', { fragment: horizontalFragments[0] } );
1193 * Navigate to the previous slide fragment.
1195 * @return {Boolean} true if there was a previous fragment,
1198 function previousFragment() {
1200 if( document.querySelector( VERTICAL_SLIDES_SELECTOR + '.present' ) ) {
1201 var verticalFragments = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR + '.present .fragment.visible' );
1202 if( verticalFragments.length ) {
1203 verticalFragments[ verticalFragments.length - 1 ].classList.remove( 'visible' );
1205 // Notify subscribers of the change
1206 dispatchEvent( 'fragmenthidden', { fragment: verticalFragments[ verticalFragments.length - 1 ] } );
1210 // Horizontal slides:
1212 var horizontalFragments = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.present .fragment.visible' );
1213 if( horizontalFragments.length ) {
1214 horizontalFragments[ horizontalFragments.length - 1 ].classList.remove( 'visible' );
1216 // Notify subscribers of the change
1217 dispatchEvent( 'fragmenthidden', { fragment: horizontalFragments[ horizontalFragments.length - 1 ] } );
1226 * Cues a new automated slide if enabled in the config.
1228 function cueAutoSlide() {
1229 clearTimeout( autoSlideTimeout );
1231 // Cue the next auto-slide if enabled
1233 autoSlideTimeout = setTimeout( navigateNext, autoSlide );
1237 function navigateLeft() {
1238 // Prioritize hiding fragments
1239 if( availableRoutes().left && isOverviewActive() || previousFragment() === false ) {
1240 slide( indexh - 1 );
1244 function navigateRight() {
1245 // Prioritize revealing fragments
1246 if( availableRoutes().right && isOverviewActive() || nextFragment() === false ) {
1247 slide( indexh + 1 );
1251 function navigateUp() {
1252 // Prioritize hiding fragments
1253 if( availableRoutes().up && isOverviewActive() || previousFragment() === false ) {
1254 slide( indexh, indexv - 1 );
1258 function navigateDown() {
1259 // Prioritize revealing fragments
1260 if( availableRoutes().down && isOverviewActive() || nextFragment() === false ) {
1261 slide( indexh, indexv + 1 );
1266 * Navigates backwards, prioritized in the following order:
1267 * 1) Previous fragment
1268 * 2) Previous vertical slide
1269 * 3) Previous horizontal slide
1271 function navigatePrev() {
1272 // Prioritize revealing fragments
1273 if( previousFragment() === false ) {
1274 if( availableRoutes().up ) {
1278 // Fetch the previous horizontal slide, if there is one
1279 var previousSlide = document.querySelector( HORIZONTAL_SLIDES_SELECTOR + '.past:nth-child(' + indexh + ')' );
1281 if( previousSlide ) {
1282 indexv = ( previousSlide.querySelectorAll( 'section' ).length + 1 ) || undefined;
1291 * Same as #navigatePrev() but navigates forwards.
1293 function navigateNext() {
1294 // Prioritize revealing fragments
1295 if( nextFragment() === false ) {
1296 availableRoutes().down ? navigateDown() : navigateRight();
1299 // If auto-sliding is enabled we need to cue up
1305 // --------------------------------------------------------------------//
1306 // ----------------------------- EVENTS -------------------------------//
1307 // --------------------------------------------------------------------//
1311 * Handler for the document level 'keydown' event.
1313 * @param {Object} event
1315 function onDocumentKeyDown( event ) {
1316 // Check if there's a focused element that could be using
1318 var activeElement = document.activeElement;
1319 var hasFocus = !!( document.activeElement && ( document.activeElement.type || document.activeElement.href || document.activeElement.contentEditable !== 'inherit' ) );
1321 // Disregard the event if there's a focused element or a
1322 // keyboard modifier key is present
1323 if ( hasFocus || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey ) return;
1325 var triggered = true;
1327 switch( event.keyCode ) {
1329 case 80: case 33: navigatePrev(); break;
1331 case 78: case 34: navigateNext(); break;
1333 case 72: case 37: navigateLeft(); break;
1335 case 76: case 39: navigateRight(); break;
1337 case 75: case 38: navigateUp(); break;
1339 case 74: case 40: navigateDown(); break;
1341 case 36: slide( 0 ); break;
1343 case 35: slide( Number.MAX_VALUE ); break;
1345 case 32: isOverviewActive() ? deactivateOverview() : navigateNext(); break;
1347 case 13: isOverviewActive() ? deactivateOverview() : triggered = false; break;
1349 case 66: case 190: togglePause(); break;
1351 case 70: enterFullscreen(); break;
1356 // If the input resulted in a triggered action we should prevent
1357 // the browsers default behavior
1359 event.preventDefault();
1361 else if ( event.keyCode === 27 && supports3DTransforms ) {
1364 event.preventDefault();
1367 // If auto-sliding is enabled we need to cue up
1374 * Handler for the document level 'touchstart' event,
1375 * enables support for swipe and pinch gestures.
1377 function onDocumentTouchStart( event ) {
1378 touch.startX = event.touches[0].clientX;
1379 touch.startY = event.touches[0].clientY;
1380 touch.startCount = event.touches.length;
1382 // If there's two touches we need to memorize the distance
1383 // between those two points to detect pinching
1384 if( event.touches.length === 2 && config.overview ) {
1385 touch.startSpan = distanceBetween( {
1386 x: event.touches[1].clientX,
1387 y: event.touches[1].clientY
1396 * Handler for the document level 'touchmove' event.
1398 function onDocumentTouchMove( event ) {
1399 // Each touch should only trigger one action
1400 if( !touch.handled ) {
1401 var currentX = event.touches[0].clientX;
1402 var currentY = event.touches[0].clientY;
1404 // If the touch started off with two points and still has
1405 // two active touches; test for the pinch gesture
1406 if( event.touches.length === 2 && touch.startCount === 2 && config.overview ) {
1408 // The current distance in pixels between the two touch points
1409 var currentSpan = distanceBetween( {
1410 x: event.touches[1].clientX,
1411 y: event.touches[1].clientY
1417 // If the span is larger than the desire amount we've got
1418 // ourselves a pinch
1419 if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) {
1420 touch.handled = true;
1422 if( currentSpan < touch.startSpan ) {
1426 deactivateOverview();
1430 event.preventDefault();
1433 // There was only one touch point, look for a swipe
1434 else if( event.touches.length === 1 && touch.startCount !== 2 ) {
1436 var deltaX = currentX - touch.startX,
1437 deltaY = currentY - touch.startY;
1439 if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
1440 touch.handled = true;
1443 else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
1444 touch.handled = true;
1447 else if( deltaY > touch.threshold ) {
1448 touch.handled = true;
1451 else if( deltaY < -touch.threshold ) {
1452 touch.handled = true;
1456 event.preventDefault();
1460 // There's a bug with swiping on some Android devices unless
1461 // the default action is always prevented
1462 else if( navigator.userAgent.match( /android/gi ) ) {
1463 event.preventDefault();
1468 * Handler for the document level 'touchend' event.
1470 function onDocumentTouchEnd( event ) {
1471 touch.handled = false;
1475 * Handles mouse wheel scrolling, throttled to avoid skipping
1478 function onDocumentMouseScroll( event ){
1479 clearTimeout( mouseWheelTimeout );
1481 mouseWheelTimeout = setTimeout( function() {
1482 var delta = event.detail || -event.wheelDelta;
1493 * Clicking on the progress bar results in a navigation to the
1494 * closest approximate horizontal slide using this equation:
1496 * ( clickX / presentationWidth ) * numberOfSlides
1498 function onProgressClick( event ) {
1499 var slidesTotal = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length;
1500 var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal );
1502 slide( slideIndex );
1506 * Handler for the window level 'hashchange' event.
1508 function onWindowHashChange( event ) {
1513 * Handler for the window level 'resize' event.
1515 function onWindowResize( event ) {
1520 * Invoked when a slide is and we're in the overview.
1522 function onOverviewSlideClicked( event ) {
1523 // TODO There's a bug here where the event listeners are not
1524 // removed after deactivating the overview.
1525 if( isOverviewActive() ) {
1526 event.preventDefault();
1528 deactivateOverview();
1530 var h = parseInt( event.target.getAttribute( 'data-index-h' ), 10 ),
1531 v = parseInt( event.target.getAttribute( 'data-index-v' ), 10 );
1538 // --------------------------------------------------------------------//
1539 // ------------------------------- API --------------------------------//
1540 // --------------------------------------------------------------------//
1544 initialize: initialize,
1546 // Navigation methods
1549 right: navigateRight,
1554 prevFragment: previousFragment,
1555 nextFragment: nextFragment,
1557 // Deprecated aliases
1559 navigateLeft: navigateLeft,
1560 navigateRight: navigateRight,
1561 navigateUp: navigateUp,
1562 navigateDown: navigateDown,
1563 navigatePrev: navigatePrev,
1564 navigateNext: navigateNext,
1566 // Toggles the overview mode on/off
1567 toggleOverview: toggleOverview,
1569 // Adds or removes all internal event listeners (such as keyboard)
1570 addEventListeners: addEventListeners,
1571 removeEventListeners: removeEventListeners,
1573 // Returns the indices of the current, or specified, slide
1574 getIndices: getIndices,
1576 // Returns the previous slide element, may be null
1577 getPreviousSlide: function() {
1578 return previousSlide;
1581 // Returns the current slide element
1582 getCurrentSlide: function() {
1583 return currentSlide;
1586 // Helper method, retrieves query string as a key/value hash
1587 getQueryHash: function() {
1590 location.search.replace( /[A-Z0-9]+?=(\w*)/gi, function(a) {
1591 query[ a.split( '=' ).shift() ] = a.split( '=' ).pop();
1597 // Forward event binding to the reveal DOM element
1598 addEventListener: function( type, listener, useCapture ) {
1599 if( 'addEventListener' in window ) {
1600 ( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture );
1603 removeEventListener: function( type, listener, useCapture ) {
1604 if( 'addEventListener' in window ) {
1605 ( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture );