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 // Change the presentation direction to be 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 // A delay used to ativate the overview mode
106 activateOverviewTimeout = 0,
108 // Holds information about the currently ongoing touch input
119 * Starts up the presentation if the client is capable.
121 function initialize( options ) {
122 if( ( !supports2DTransforms && !supports3DTransforms ) ) {
123 document.body.setAttribute( 'class', 'no-transforms' );
125 // If the browser doesn't support core features we won't be
126 // using JavaScript to control the presentation
130 // Force a layout when the whole page, incl fonts, has loaded
131 window.addEventListener( 'load', layout, false );
133 // Copy options over to our config object
134 extend( config, options );
136 // Hide the address bar in mobile browsers
139 // Loads the dependencies and continues to #start() once done
145 * Finds and stores references to DOM elements which are
146 * required by the presentation. If a required element is
147 * not found, it is created.
149 function setupDOM() {
150 // Cache references to key DOM elements
151 dom.theme = document.querySelector( '#theme' );
152 dom.wrapper = document.querySelector( '.reveal' );
153 dom.slides = document.querySelector( '.reveal .slides' );
156 if( !dom.wrapper.querySelector( '.progress' ) && config.progress ) {
157 var progressElement = document.createElement( 'div' );
158 progressElement.classList.add( 'progress' );
159 progressElement.innerHTML = '<span></span>';
160 dom.wrapper.appendChild( progressElement );
164 if( !dom.wrapper.querySelector( '.controls' ) && config.controls ) {
165 var controlsElement = document.createElement( 'aside' );
166 controlsElement.classList.add( 'controls' );
167 controlsElement.innerHTML = '<div class="navigate-left"></div>' +
168 '<div class="navigate-right"></div>' +
169 '<div class="navigate-up"></div>' +
170 '<div class="navigate-down"></div>';
171 dom.wrapper.appendChild( controlsElement );
174 // Presentation background element
175 if( !dom.wrapper.querySelector( '.state-background' ) ) {
176 var backgroundElement = document.createElement( 'div' );
177 backgroundElement.classList.add( 'state-background' );
178 dom.wrapper.appendChild( backgroundElement );
181 // Overlay graphic which is displayed during the paused mode
182 if( !dom.wrapper.querySelector( '.pause-overlay' ) ) {
183 var pausedElement = document.createElement( 'div' );
184 pausedElement.classList.add( 'pause-overlay' );
185 dom.wrapper.appendChild( pausedElement );
188 // Cache references to elements
189 dom.progress = document.querySelector( '.reveal .progress' );
190 dom.progressbar = document.querySelector( '.reveal .progress span' );
192 if ( config.controls ) {
193 dom.controls = document.querySelector( '.reveal .controls' );
195 // There can be multiple instances of controls throughout the page
196 dom.controlsLeft = toArray( document.querySelectorAll( '.navigate-left' ) );
197 dom.controlsRight = toArray( document.querySelectorAll( '.navigate-right' ) );
198 dom.controlsUp = toArray( document.querySelectorAll( '.navigate-up' ) );
199 dom.controlsDown = toArray( document.querySelectorAll( '.navigate-down' ) );
200 dom.controlsPrev = toArray( document.querySelectorAll( '.navigate-prev' ) );
201 dom.controlsNext = toArray( document.querySelectorAll( '.navigate-next' ) );
206 * Hides the address bar if we're on a mobile device.
208 function hideAddressBar() {
209 if( navigator.userAgent.match( /(iphone|ipod)/i ) ) {
210 // Give the page some scrollable overflow
211 document.documentElement.style.overflow = 'scroll';
212 document.body.style.height = '120%';
214 // Events that should trigger the address bar to hide
215 window.addEventListener( 'load', removeAddressBar, false );
216 window.addEventListener( 'orientationchange', removeAddressBar, false );
221 * Loads the dependencies of reveal.js. Dependencies are
222 * defined via the configuration option 'dependencies'
223 * and will be loaded prior to starting/binding reveal.js.
224 * Some dependencies may have an 'async' flag, if so they
225 * will load after reveal.js has been started up.
231 for( var i = 0, len = config.dependencies.length; i < len; i++ ) {
232 var s = config.dependencies[i];
234 // Load if there's no condition or the condition is truthy
235 if( !s.condition || s.condition() ) {
237 scriptsAsync.push( s.src );
240 scripts.push( s.src );
243 // Extension may contain callback functions
244 if( typeof s.callback === 'function' ) {
245 head.ready( s.src.match( /([\w\d_\-]*)\.?js$|[^\\\/]*$/i )[0], s.callback );
250 // Called once synchronous scritps finish loading
252 if( scriptsAsync.length ) {
253 // Load asynchronous scripts
254 head.js.apply( null, scriptsAsync );
260 if( scripts.length ) {
261 head.ready( proceed );
263 // Load synchronous scripts
264 head.js.apply( null, scripts );
272 * Starts up reveal.js by binding input events and navigating
273 * to the current URL deeplink if there is one.
276 // Make sure we've got all the DOM elements we need
279 // Subscribe to input
282 // Updates the presentation to match the current configuration values
285 // Force an initial layout, will thereafter be invoked as the window
289 // Read the initial hash
292 // Start auto-sliding if it's enabled
295 // Notify listeners that the presentation is ready but use a 1ms
296 // timeout to ensure it's not fired synchronously after #initialize()
297 setTimeout( function() {
298 dispatchEvent( 'ready', {
301 'currentSlide': currentSlide
307 * Applies the configuration settings from the config object.
309 function configure() {
310 if( supports3DTransforms === false ) {
311 config.transition = 'linear';
314 if( config.controls && dom.controls ) {
315 dom.controls.style.display = 'block';
318 if( config.progress && dom.progress ) {
319 dom.progress.style.display = 'block';
322 if( config.transition !== 'default' ) {
323 dom.wrapper.classList.add( config.transition );
327 dom.wrapper.classList.add( 'rtl' );
330 if( config.center ) {
331 dom.wrapper.classList.add( 'center' );
334 if( config.mouseWheel ) {
335 document.addEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
336 document.addEventListener( 'mousewheel', onDocumentMouseScroll, false );
340 if( config.rollingLinks ) {
344 // Load the theme in the config, if it's not already loaded
345 if( config.theme && dom.theme ) {
346 var themeURL = dom.theme.getAttribute( 'href' );
347 var themeFinder = /[^\/]*?(?=\.css)/;
348 var themeName = themeURL.match(themeFinder)[0];
350 if( config.theme !== themeName ) {
351 themeURL = themeURL.replace(themeFinder, config.theme);
352 dom.theme.setAttribute( 'href', themeURL );
358 * Binds all event listeners.
360 function addEventListeners() {
361 document.addEventListener( 'touchstart', onDocumentTouchStart, false );
362 document.addEventListener( 'touchmove', onDocumentTouchMove, false );
363 document.addEventListener( 'touchend', onDocumentTouchEnd, false );
364 window.addEventListener( 'hashchange', onWindowHashChange, false );
365 window.addEventListener( 'resize', onWindowResize, false );
367 if( config.keyboard ) {
368 document.addEventListener( 'keydown', onDocumentKeyDown, false );
371 if ( config.progress && dom.progress ) {
372 dom.progress.addEventListener( 'click', preventAndForward( onProgressClick ), false );
375 if ( config.controls && dom.controls ) {
376 var actionEvent = 'ontouchstart' in window ? 'touchstart' : 'click';
377 dom.controlsLeft.forEach( function( el ) { el.addEventListener( actionEvent, preventAndForward( navigateLeft ), false ); } );
378 dom.controlsRight.forEach( function( el ) { el.addEventListener( actionEvent, preventAndForward( navigateRight ), false ); } );
379 dom.controlsUp.forEach( function( el ) { el.addEventListener( actionEvent, preventAndForward( navigateUp ), false ); } );
380 dom.controlsDown.forEach( function( el ) { el.addEventListener( actionEvent, preventAndForward( navigateDown ), false ); } );
381 dom.controlsPrev.forEach( function( el ) { el.addEventListener( actionEvent, preventAndForward( navigatePrev ), false ); } );
382 dom.controlsNext.forEach( function( el ) { el.addEventListener( actionEvent, preventAndForward( navigateNext ), false ); } );
387 * Unbinds all event listeners.
389 function removeEventListeners() {
390 document.removeEventListener( 'keydown', onDocumentKeyDown, false );
391 document.removeEventListener( 'touchstart', onDocumentTouchStart, false );
392 document.removeEventListener( 'touchmove', onDocumentTouchMove, false );
393 document.removeEventListener( 'touchend', onDocumentTouchEnd, false );
394 window.removeEventListener( 'hashchange', onWindowHashChange, false );
395 window.removeEventListener( 'resize', onWindowResize, false );
397 if ( config.progress && dom.progress ) {
398 dom.progress.removeEventListener( 'click', preventAndForward( onProgressClick ), false );
401 if ( config.controls && dom.controls ) {
402 var actionEvent = 'ontouchstart' in window ? 'touchstart' : 'click';
403 dom.controlsLeft.forEach( function( el ) { el.removeEventListener( actionEvent, preventAndForward( navigateLeft ), false ); } );
404 dom.controlsRight.forEach( function( el ) { el.removeEventListener( actionEvent, preventAndForward( navigateRight ), false ); } );
405 dom.controlsUp.forEach( function( el ) { el.removeEventListener( actionEvent, preventAndForward( navigateUp ), false ); } );
406 dom.controlsDown.forEach( function( el ) { el.removeEventListener( actionEvent, preventAndForward( navigateDown ), false ); } );
407 dom.controlsPrev.forEach( function( el ) { el.removeEventListener( actionEvent, preventAndForward( navigatePrev ), false ); } );
408 dom.controlsNext.forEach( function( el ) { el.removeEventListener( actionEvent, preventAndForward( navigateNext ), false ); } );
413 * Extend object a with the properties of object b.
414 * If there's a conflict, object b takes precedence.
416 function extend( a, b ) {
423 * Converts the target object to an array.
425 function toArray( o ) {
426 return Array.prototype.slice.call( o );
429 function each( targets, method, args ) {
430 targets.forEach( function( el ) {
431 el[method].apply( el, args );
436 * Measures the distance in pixels between point a
439 * @param {Object} a point with x/y properties
440 * @param {Object} b point with x/y properties
442 function distanceBetween( a, b ) {
446 return Math.sqrt( dx*dx + dy*dy );
450 * Prevents an events defaults behavior calls the
451 * specified delegate.
453 * @param {Function} delegate The method to call
454 * after the wrapper has been executed
456 function preventAndForward( delegate ) {
457 return function( event ) {
458 event.preventDefault();
459 delegate.call( null, event );
464 * Causes the address bar to hide on mobile devices,
465 * more vertical space ftw.
467 function removeAddressBar() {
468 setTimeout( function() {
469 window.scrollTo( 0, 1 );
474 * Dispatches an event of the specified type from the
475 * reveal DOM element.
477 function dispatchEvent( type, properties ) {
478 var event = document.createEvent( "HTMLEvents", 1, 2 );
479 event.initEvent( type, true, true );
480 extend( event, properties );
481 dom.wrapper.dispatchEvent( event );
485 * Wrap all links in 3D goodness.
488 if( supports3DTransforms && !( 'msPerspective' in document.body.style ) ) {
489 var nodes = document.querySelectorAll( SLIDES_SELECTOR + ' a:not(.image)' );
491 for( var i = 0, len = nodes.length; i < len; i++ ) {
494 if( node.textContent && !node.querySelector( 'img' ) && ( !node.className || !node.classList.contains( node, 'roll' ) ) ) {
495 var span = document.createElement('span');
496 span.setAttribute('data-title', node.text);
497 span.innerHTML = node.innerHTML;
499 node.classList.add( 'roll' );
501 node.appendChild(span);
508 * Applies JavaScript-controlled layout rules to the
513 if( config.center ) {
515 // Select all slides, vertical and horizontal
516 var slides = toArray( document.querySelectorAll( SLIDES_SELECTOR ) );
518 // Determine the minimum top offset for slides
519 var minTop = -dom.wrapper.offsetHeight / 2;
521 for( var i = 0, len = slides.length; i < len; i++ ) {
522 var slide = slides[ i ];
524 // Don't bother update invisible slides
525 if( slide.style.display === 'none' ) {
529 // Vertical stacks are not centered since their section
531 if( slide.classList.contains( 'stack' ) ) {
535 slide.style.top = Math.max( - ( slide.offsetHeight / 2 ) - 20, minTop ) + 'px';
544 * Stores the vertical index of a stack so that the same
545 * vertical slide can be selected when navigating to and
548 * @param {HTMLElement} stack The vertical stack element
549 * @param {int} v Index to memorize
551 function setPreviousVerticalIndex( stack, v ) {
553 stack.setAttribute( 'data-previous-indexv', v || 0 );
558 * Retrieves the vertical index which was stored using
559 * #setPreviousVerticalIndex() or 0 if no previous index
562 * @param {HTMLElement} stack The vertical stack element
564 function getPreviousVerticalIndex( stack ) {
565 if( stack && stack.classList.contains( 'stack' ) ) {
566 return parseInt( stack.getAttribute( 'data-previous-indexv' ) || 0, 10 );
573 * Displays the overview of slides (quick nav) by
574 * scaling down and arranging all slide elements.
576 * Experimental feature, might be dropped if perf
579 function activateOverview() {
581 // Only proceed if enabled in config
582 if( config.overview ) {
584 dom.wrapper.classList.add( 'overview' );
586 clearTimeout( activateOverviewTimeout );
588 // Not the pretties solution, but need to let the overview
589 // class apply first so that slides are measured accurately
590 // before we can positon them
591 activateOverviewTimeout = setTimeout( function(){
593 var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
595 for( var i = 0, len1 = horizontalSlides.length; i < len1; i++ ) {
596 var hslide = horizontalSlides[i],
597 htransform = 'translateZ(-2500px) translate(' + ( ( i - indexh ) * 105 ) + '%, 0%)';
599 hslide.setAttribute( 'data-index-h', i );
600 hslide.style.display = 'block';
601 hslide.style.WebkitTransform = htransform;
602 hslide.style.MozTransform = htransform;
603 hslide.style.msTransform = htransform;
604 hslide.style.OTransform = htransform;
605 hslide.style.transform = htransform;
607 if( hslide.classList.contains( 'stack' ) ) {
609 var verticalSlides = hslide.querySelectorAll( 'section' );
611 for( var j = 0, len2 = verticalSlides.length; j < len2; j++ ) {
612 var verticalIndex = i === indexh ? indexv : getPreviousVerticalIndex( hslide );
614 var vslide = verticalSlides[j],
615 vtransform = 'translate(0%, ' + ( ( j - verticalIndex ) * 105 ) + '%)';
617 vslide.setAttribute( 'data-index-h', i );
618 vslide.setAttribute( 'data-index-v', j );
619 vslide.style.display = 'block';
620 vslide.style.WebkitTransform = vtransform;
621 vslide.style.MozTransform = vtransform;
622 vslide.style.msTransform = vtransform;
623 vslide.style.OTransform = vtransform;
624 vslide.style.transform = vtransform;
626 // Navigate to this slide on click
627 vslide.addEventListener( 'click', onOverviewSlideClicked, true );
633 // Navigate to this slide on click
634 hslide.addEventListener( 'click', onOverviewSlideClicked, true );
648 * Exits the slide overview and enters the currently
651 function deactivateOverview() {
653 // Only proceed if enabled in config
654 if( config.overview ) {
656 clearTimeout( activateOverviewTimeout );
658 dom.wrapper.classList.remove( 'overview' );
661 var slides = toArray( document.querySelectorAll( SLIDES_SELECTOR ) );
663 for( var i = 0, len = slides.length; i < len; i++ ) {
664 var element = slides[i];
666 element.style.display = '';
668 // Resets all transforms to use the external styles
669 element.style.WebkitTransform = '';
670 element.style.MozTransform = '';
671 element.style.msTransform = '';
672 element.style.OTransform = '';
673 element.style.transform = '';
675 element.removeEventListener( 'click', onOverviewSlideClicked, true );
678 slide( indexh, indexv );
684 * Toggles the slide overview mode on and off.
686 * @param {Boolean} override Optional flag which overrides the
687 * toggle logic and forcibly sets the desired state. True means
688 * overview is open, false means it's closed.
690 function toggleOverview( override ) {
691 if( typeof override === 'boolean' ) {
692 override ? activateOverview() : deactivateOverview();
695 isOverviewActive() ? deactivateOverview() : activateOverview();
700 * Checks if the overview is currently active.
702 * @return {Boolean} true if the overview is active,
705 function isOverviewActive() {
706 return dom.wrapper.classList.contains( 'overview' );
710 * Handling the fullscreen functionality via the fullscreen API
712 * @see http://fullscreen.spec.whatwg.org/
713 * @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode
715 function enterFullscreen() {
716 var element = document.body;
718 // Check which implementation is available
719 var requestMethod = element.requestFullScreen ||
720 element.webkitRequestFullScreen ||
721 element.mozRequestFullScreen ||
722 element.msRequestFullScreen;
724 if( requestMethod ) {
725 requestMethod.apply( element );
730 * Enters the paused mode which fades everything on screen to
734 dom.wrapper.classList.add( 'paused' );
738 * Exits from the paused mode.
741 dom.wrapper.classList.remove( 'paused' );
745 * Toggles the paused mode on and off.
747 function togglePause() {
757 * Checks if we are currently in the paused mode.
759 function isPaused() {
760 return dom.wrapper.classList.contains( 'paused' );
764 * Steps from the current point in the presentation to the
765 * slide which matches the specified horizontal and vertical
768 * @param {int} h Horizontal index of the target slide
769 * @param {int} v Vertical index of the target slide
770 * @param {int} f Optional index of a fragment within the
771 * target slide to activate
773 function slide( h, v, f ) {
774 // Remember where we were at before
775 previousSlide = currentSlide;
777 // Query all horizontal slides in the deck
778 var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
780 // If no vertical index is specified and the upcoming slide is a
781 // stack, resume at its previous vertical index
782 if( v === undefined ) {
783 v = getPreviousVerticalIndex( horizontalSlides[ h ] );
786 // If we were on a vertical stack, remember what vertical index
787 // it was on so we can resume at the same position when returning
788 if( previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains( 'stack' ) ) {
789 setPreviousVerticalIndex( previousSlide.parentNode, indexv );
792 // Remember the state before this slide
793 var stateBefore = state.concat();
795 // Reset the state array
798 var indexhBefore = indexh,
799 indexvBefore = indexv;
801 // Activate and transition to the new slide
802 indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h );
803 indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v );
807 // Apply the new state
808 stateLoop: for( var i = 0, len = state.length; i < len; i++ ) {
809 // Check if this state existed on the previous slide. If it
810 // did, we will avoid adding it repeatedly
811 for( var j = 0; j < stateBefore.length; j++ ) {
812 if( stateBefore[j] === state[i] ) {
813 stateBefore.splice( j, 1 );
818 document.documentElement.classList.add( state[i] );
820 // Dispatch custom event matching the state's name
821 dispatchEvent( state[i] );
824 // Clean up the remaints of the previous state
825 while( stateBefore.length ) {
826 document.documentElement.classList.remove( stateBefore.pop() );
829 // If the overview is active, re-activate it to update positions
830 if( isOverviewActive() ) {
834 // Update the URL hash after a delay since updating it mid-transition
835 // is likely to cause visual lag
838 // Find the current horizontal slide and any possible vertical slides
840 var currentHorizontalSlide = horizontalSlides[ indexh ],
841 currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' );
843 // Store references to the previous and current slides
844 currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide;
847 // Show fragment, if specified
848 if( ( indexh !== indexhBefore || indexv !== indexvBefore ) && f ) {
849 var fragments = currentSlide.querySelectorAll( '.fragment' );
851 toArray( fragments ).forEach( function( fragment, indexf ) {
853 fragment.classList.add( 'visible' );
856 fragment.classList.remove( 'visible' );
861 // Dispatch an event if the slide changed
862 if( indexh !== indexhBefore || indexv !== indexvBefore ) {
863 dispatchEvent( 'slidechanged', {
866 'previousSlide': previousSlide,
867 'currentSlide': currentSlide
871 // Ensure that the previous slide is never the same as the current
872 previousSlide = null;
875 // Solves an edge case where the previous slide maintains the
876 // 'present' class when navigating between adjacent vertical
878 if( previousSlide ) {
879 previousSlide.classList.remove( 'present' );
887 * Updates one dimension of slides by showing the slide
888 * with the specified index.
890 * @param {String} selector A CSS selector that will fetch
891 * the group of slides we are working with
892 * @param {Number} index The index of the slide that should be
895 * @return {Number} The index of the slide that is now shown,
896 * might differ from the passed in index if it was out of
899 function updateSlides( selector, index ) {
900 // Select all slides and convert the NodeList result to
902 var slides = toArray( document.querySelectorAll( selector ) ),
903 slidesLength = slides.length;
907 // Should the index loop?
909 index %= slidesLength;
912 index = slidesLength + index;
916 // Enforce max and minimum index bounds
917 index = Math.max( Math.min( index, slidesLength - 1 ), 0 );
919 for( var i = 0; i < slidesLength; i++ ) {
920 var element = slides[i];
922 // Optimization; hide all slides that are three or more steps
923 // away from the present slide
924 if( isOverviewActive() === false ) {
925 // The distance loops so that it measures 1 between the first
927 var distance = Math.abs( ( index - i ) % ( slidesLength - 3 ) ) || 0;
929 element.style.display = distance > 3 ? 'none' : 'block';
932 slides[i].classList.remove( 'past' );
933 slides[i].classList.remove( 'present' );
934 slides[i].classList.remove( 'future' );
937 // Any element previous to index is given the 'past' class
938 slides[i].classList.add( 'past' );
940 else if( i > index ) {
941 // Any element subsequent to index is given the 'future' class
942 slides[i].classList.add( 'future' );
945 // If this element contains vertical slides
946 if( element.querySelector( 'section' ) ) {
947 slides[i].classList.add( 'stack' );
951 // Mark the current slide as present
952 slides[index].classList.add( 'present' );
954 // If this slide has a state associated with it, add it
955 // onto the current state of the deck
956 var slideState = slides[index].getAttribute( 'data-state' );
958 state = state.concat( slideState.split( ' ' ) );
961 // If this slide has a data-autoslide attribtue associated use this as
962 // autoSlide value otherwise use the global configured time
963 var slideAutoSlide = slides[index].getAttribute( 'data-autoslide' );
964 if( slideAutoSlide ) {
965 autoSlide = parseInt( slideAutoSlide, 10 );
968 autoSlide = config.autoSlide;
973 // Since there are no slides we can't be anywhere beyond the
983 * Updates the progress bar to reflect the current slide.
985 function updateProgress() {
986 // Update progress if enabled
987 if( config.progress && dom.progress ) {
989 var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
991 // The number of past and total slides
992 var totalCount = document.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length;
995 // Step through all slides and count the past ones
996 mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) {
998 var horizontalSlide = horizontalSlides[i];
999 var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
1001 for( var j = 0; j < verticalSlides.length; j++ ) {
1003 // Stop as soon as we arrive at the present
1004 if( verticalSlides[j].classList.contains( 'present' ) ) {
1012 // Stop as soon as we arrive at the present
1013 if( horizontalSlide.classList.contains( 'present' ) ) {
1017 // Don't count the wrapping section for vertical slides
1018 if( horizontalSlide.classList.contains( 'stack' ) === false ) {
1024 dom.progressbar.style.width = ( pastCount / ( totalCount - 1 ) ) * window.innerWidth + 'px';
1030 * Updates the state of all control/navigation arrows.
1032 function updateControls() {
1033 if ( config.controls && dom.controls ) {
1035 var routes = availableRoutes();
1037 // Remove the 'enabled' class from all directions
1038 dom.controlsLeft.concat( dom.controlsRight )
1039 .concat( dom.controlsUp )
1040 .concat( dom.controlsDown )
1041 .concat( dom.controlsPrev )
1042 .concat( dom.controlsNext ).forEach( function( node ) {
1043 node.classList.remove( 'enabled' );
1046 // Add the 'enabled' class to the available routes
1047 if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1048 if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1049 if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1050 if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1052 // Prev/next buttons
1053 if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1054 if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1060 * Determine what available routes there are for navigation.
1062 * @return {Object} containing four booleans: left/right/up/down
1064 function availableRoutes() {
1065 var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
1066 verticalSlides = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
1070 right: indexh < horizontalSlides.length - 1,
1072 down: indexv < verticalSlides.length - 1
1077 * Reads the current URL (hash) and navigates accordingly.
1079 function readURL() {
1080 var hash = window.location.hash;
1082 // Attempt to parse the hash as either an index or name
1083 var bits = hash.slice( 2 ).split( '/' ),
1084 name = hash.replace( /#|\//gi, '' );
1086 // If the first bit is invalid and there is a name we can
1087 // assume that this is a named link
1088 if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) {
1089 // Find the slide with the specified name
1090 var element = document.querySelector( '#' + name );
1093 // Find the position of the named slide and navigate to it
1094 var indices = Reveal.getIndices( element );
1095 slide( indices.h, indices.v );
1097 // If the slide doesn't exist, navigate to the current slide
1099 slide( indexh, indexv );
1103 // Read the index components of the hash
1104 var h = parseInt( bits[0], 10 ) || 0,
1105 v = parseInt( bits[1], 10 ) || 0;
1112 * Updates the page URL (hash) to reflect the current
1115 * @param {Number} delay The time in ms to wait before
1118 function writeURL( delay ) {
1119 if( config.history ) {
1121 // Make sure there's never more than one timeout running
1122 clearTimeout( writeURLTimeout );
1124 // If a delay is specified, timeout this call
1125 if( typeof delay === 'number' ) {
1126 writeURLTimeout = setTimeout( writeURL, delay );
1131 // If the current slide has an ID, use that as a named link
1132 if( currentSlide && typeof currentSlide.getAttribute( 'id' ) === 'string' ) {
1133 url = '/' + currentSlide.getAttribute( 'id' );
1135 // Otherwise use the /h/v index
1137 if( indexh > 0 || indexv > 0 ) url += indexh;
1138 if( indexv > 0 ) url += '/' + indexv;
1141 window.location.hash = url;
1147 * Retrieves the h/v location of the current, or specified,
1150 * @param {HTMLElement} slide If specified, the returned
1151 * index will be for this slide rather than the currently
1154 * @return {Object} { h: <int>, v: <int> }
1156 function getIndices( slide ) {
1157 // By default, return the current indices
1161 // If a slide is specified, return the indices of that slide
1163 var isVertical = !!slide.parentNode.nodeName.match( /section/gi );
1164 var slideh = isVertical ? slide.parentNode : slide;
1166 // Select all horizontal slides
1167 var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
1169 // Now that we know which the horizontal slide is, get its index
1170 h = Math.max( horizontalSlides.indexOf( slideh ), 0 );
1172 // If this is a vertical slide, grab the vertical index
1174 v = Math.max( toArray( slide.parentNode.querySelectorAll( 'section' ) ).indexOf( slide ), 0 );
1178 return { h: h, v: v };
1182 * Navigate to the next slide fragment.
1184 * @return {Boolean} true if there was a next fragment,
1187 function nextFragment() {
1189 if( document.querySelector( VERTICAL_SLIDES_SELECTOR + '.present' ) ) {
1190 var verticalFragments = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR + '.present .fragment:not(.visible)' );
1191 if( verticalFragments.length ) {
1192 verticalFragments[0].classList.add( 'visible' );
1194 // Notify subscribers of the change
1195 dispatchEvent( 'fragmentshown', { fragment: verticalFragments[0] } );
1199 // Horizontal slides:
1201 var horizontalFragments = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.present .fragment:not(.visible)' );
1202 if( horizontalFragments.length ) {
1203 horizontalFragments[0].classList.add( 'visible' );
1205 // Notify subscribers of the change
1206 dispatchEvent( 'fragmentshown', { fragment: horizontalFragments[0] } );
1215 * Navigate to the previous slide fragment.
1217 * @return {Boolean} true if there was a previous fragment,
1220 function previousFragment() {
1222 if( document.querySelector( VERTICAL_SLIDES_SELECTOR + '.present' ) ) {
1223 var verticalFragments = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR + '.present .fragment.visible' );
1224 if( verticalFragments.length ) {
1225 verticalFragments[ verticalFragments.length - 1 ].classList.remove( 'visible' );
1227 // Notify subscribers of the change
1228 dispatchEvent( 'fragmenthidden', { fragment: verticalFragments[ verticalFragments.length - 1 ] } );
1232 // Horizontal slides:
1234 var horizontalFragments = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.present .fragment.visible' );
1235 if( horizontalFragments.length ) {
1236 horizontalFragments[ horizontalFragments.length - 1 ].classList.remove( 'visible' );
1238 // Notify subscribers of the change
1239 dispatchEvent( 'fragmenthidden', { fragment: horizontalFragments[ horizontalFragments.length - 1 ] } );
1248 * Cues a new automated slide if enabled in the config.
1250 function cueAutoSlide() {
1251 clearTimeout( autoSlideTimeout );
1253 // Cue the next auto-slide if enabled
1255 autoSlideTimeout = setTimeout( navigateNext, autoSlide );
1259 function navigateLeft() {
1260 // Prioritize hiding fragments
1261 if( availableRoutes().left && isOverviewActive() || previousFragment() === false ) {
1262 slide( indexh - 1 );
1266 function navigateRight() {
1267 // Prioritize revealing fragments
1268 if( availableRoutes().right && isOverviewActive() || nextFragment() === false ) {
1269 slide( indexh + 1 );
1273 function navigateUp() {
1274 // Prioritize hiding fragments
1275 if( availableRoutes().up && isOverviewActive() || previousFragment() === false ) {
1276 slide( indexh, indexv - 1 );
1280 function navigateDown() {
1281 // Prioritize revealing fragments
1282 if( availableRoutes().down && isOverviewActive() || nextFragment() === false ) {
1283 slide( indexh, indexv + 1 );
1288 * Navigates backwards, prioritized in the following order:
1289 * 1) Previous fragment
1290 * 2) Previous vertical slide
1291 * 3) Previous horizontal slide
1293 function navigatePrev() {
1294 // Prioritize revealing fragments
1295 if( previousFragment() === false ) {
1296 if( availableRoutes().up ) {
1300 // Fetch the previous horizontal slide, if there is one
1301 var previousSlide = document.querySelector( HORIZONTAL_SLIDES_SELECTOR + '.past:nth-child(' + indexh + ')' );
1303 if( previousSlide ) {
1304 indexv = ( previousSlide.querySelectorAll( 'section' ).length + 1 ) || undefined;
1313 * Same as #navigatePrev() but navigates forwards.
1315 function navigateNext() {
1316 // Prioritize revealing fragments
1317 if( nextFragment() === false ) {
1318 availableRoutes().down ? navigateDown() : navigateRight();
1321 // If auto-sliding is enabled we need to cue up
1327 // --------------------------------------------------------------------//
1328 // ----------------------------- EVENTS -------------------------------//
1329 // --------------------------------------------------------------------//
1333 * Handler for the document level 'keydown' event.
1335 * @param {Object} event
1337 function onDocumentKeyDown( event ) {
1338 // Check if there's a focused element that could be using
1340 var activeElement = document.activeElement;
1341 var hasFocus = !!( document.activeElement && ( document.activeElement.type || document.activeElement.href || document.activeElement.contentEditable !== 'inherit' ) );
1343 // Disregard the event if there's a focused element or a
1344 // keyboard modifier key is present
1345 if ( hasFocus || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey ) return;
1347 var triggered = true;
1349 switch( event.keyCode ) {
1351 case 80: case 33: navigatePrev(); break;
1353 case 78: case 34: navigateNext(); break;
1355 case 72: case 37: navigateLeft(); break;
1357 case 76: case 39: navigateRight(); break;
1359 case 75: case 38: navigateUp(); break;
1361 case 74: case 40: navigateDown(); break;
1363 case 36: slide( 0 ); break;
1365 case 35: slide( Number.MAX_VALUE ); break;
1367 case 32: isOverviewActive() ? deactivateOverview() : navigateNext(); break;
1369 case 13: isOverviewActive() ? deactivateOverview() : triggered = false; break;
1371 case 66: case 190: togglePause(); break;
1373 case 70: enterFullscreen(); break;
1378 // If the input resulted in a triggered action we should prevent
1379 // the browsers default behavior
1381 event.preventDefault();
1383 else if ( event.keyCode === 27 && supports3DTransforms ) {
1386 event.preventDefault();
1389 // If auto-sliding is enabled we need to cue up
1396 * Handler for the document level 'touchstart' event,
1397 * enables support for swipe and pinch gestures.
1399 function onDocumentTouchStart( event ) {
1400 touch.startX = event.touches[0].clientX;
1401 touch.startY = event.touches[0].clientY;
1402 touch.startCount = event.touches.length;
1404 // If there's two touches we need to memorize the distance
1405 // between those two points to detect pinching
1406 if( event.touches.length === 2 && config.overview ) {
1407 touch.startSpan = distanceBetween( {
1408 x: event.touches[1].clientX,
1409 y: event.touches[1].clientY
1418 * Handler for the document level 'touchmove' event.
1420 function onDocumentTouchMove( event ) {
1421 // Each touch should only trigger one action
1422 if( !touch.handled ) {
1423 var currentX = event.touches[0].clientX;
1424 var currentY = event.touches[0].clientY;
1426 // If the touch started off with two points and still has
1427 // two active touches; test for the pinch gesture
1428 if( event.touches.length === 2 && touch.startCount === 2 && config.overview ) {
1430 // The current distance in pixels between the two touch points
1431 var currentSpan = distanceBetween( {
1432 x: event.touches[1].clientX,
1433 y: event.touches[1].clientY
1439 // If the span is larger than the desire amount we've got
1440 // ourselves a pinch
1441 if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) {
1442 touch.handled = true;
1444 if( currentSpan < touch.startSpan ) {
1448 deactivateOverview();
1452 event.preventDefault();
1455 // There was only one touch point, look for a swipe
1456 else if( event.touches.length === 1 && touch.startCount !== 2 ) {
1458 var deltaX = currentX - touch.startX,
1459 deltaY = currentY - touch.startY;
1461 if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
1462 touch.handled = true;
1465 else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
1466 touch.handled = true;
1469 else if( deltaY > touch.threshold ) {
1470 touch.handled = true;
1473 else if( deltaY < -touch.threshold ) {
1474 touch.handled = true;
1478 event.preventDefault();
1482 // There's a bug with swiping on some Android devices unless
1483 // the default action is always prevented
1484 else if( navigator.userAgent.match( /android/gi ) ) {
1485 event.preventDefault();
1490 * Handler for the document level 'touchend' event.
1492 function onDocumentTouchEnd( event ) {
1493 touch.handled = false;
1497 * Handles mouse wheel scrolling, throttled to avoid skipping
1500 function onDocumentMouseScroll( event ){
1501 clearTimeout( mouseWheelTimeout );
1503 mouseWheelTimeout = setTimeout( function() {
1504 var delta = event.detail || -event.wheelDelta;
1515 * Clicking on the progress bar results in a navigation to the
1516 * closest approximate horizontal slide using this equation:
1518 * ( clickX / presentationWidth ) * numberOfSlides
1520 function onProgressClick( event ) {
1521 var slidesTotal = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length;
1522 var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal );
1524 slide( slideIndex );
1528 * Handler for the window level 'hashchange' event.
1530 function onWindowHashChange( event ) {
1535 * Handler for the window level 'resize' event.
1537 function onWindowResize( event ) {
1542 * Invoked when a slide is and we're in the overview.
1544 function onOverviewSlideClicked( event ) {
1545 // TODO There's a bug here where the event listeners are not
1546 // removed after deactivating the overview.
1547 if( isOverviewActive() ) {
1548 event.preventDefault();
1550 deactivateOverview();
1552 var element = event.target;
1554 while( element && !element.nodeName.match( /section/gi ) ) {
1555 element = element.parentNode;
1558 if( element.nodeName.match( /section/gi ) ) {
1559 var h = parseInt( element.getAttribute( 'data-index-h' ), 10 ),
1560 v = parseInt( element.getAttribute( 'data-index-v' ), 10 );
1568 // --------------------------------------------------------------------//
1569 // ------------------------------- API --------------------------------//
1570 // --------------------------------------------------------------------//
1574 initialize: initialize,
1576 // Navigation methods
1579 right: navigateRight,
1584 prevFragment: previousFragment,
1585 nextFragment: nextFragment,
1587 // Deprecated aliases
1589 navigateLeft: navigateLeft,
1590 navigateRight: navigateRight,
1591 navigateUp: navigateUp,
1592 navigateDown: navigateDown,
1593 navigatePrev: navigatePrev,
1594 navigateNext: navigateNext,
1596 // Toggles the overview mode on/off
1597 toggleOverview: toggleOverview,
1599 // Adds or removes all internal event listeners (such as keyboard)
1600 addEventListeners: addEventListeners,
1601 removeEventListeners: removeEventListeners,
1603 // Returns the indices of the current, or specified, slide
1604 getIndices: getIndices,
1606 // Returns the previous slide element, may be null
1607 getPreviousSlide: function() {
1608 return previousSlide;
1611 // Returns the current slide element
1612 getCurrentSlide: function() {
1613 return currentSlide;
1616 // Helper method, retrieves query string as a key/value hash
1617 getQueryHash: function() {
1620 location.search.replace( /[A-Z0-9]+?=(\w*)/gi, function(a) {
1621 query[ a.split( '=' ).shift() ] = a.split( '=' ).pop();
1627 // Forward event binding to the reveal DOM element
1628 addEventListener: function( type, listener, useCapture ) {
1629 if( 'addEventListener' in window ) {
1630 ( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture );
1633 removeEventListener: function( type, listener, useCapture ) {
1634 if( 'addEventListener' in window ) {
1635 ( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture );