slideshow.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. /**
  2. * Copyright (C) 2011 Hakim El Hattab, http://hakim.se
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. /**
  23. * Handles the very minimal navigation logic involved in the
  24. * slideshow. Including keyboard navigation, touch interaction
  25. * and URL history behavior.
  26. *
  27. * Slides are given unique hash based URL's so that they can be
  28. * opened directly. I didn't use the HTML5 History API for this
  29. * as it would have required the addition of server side rewrite
  30. * rules and hence require more effort for anyone to set up.
  31. *
  32. * This component can be called from other scripts via a tiny API:
  33. * - Slideshow.navigateTo( indexh, indexv );
  34. * - Slideshow.navigateLeft();
  35. * - Slideshow.navigateRight();
  36. * - Slideshow.navigateUp();
  37. * - Slideshow.navigateDown();
  38. *
  39. *
  40. * version 0.1:
  41. * - First release
  42. *
  43. * version 0.2:
  44. * - Refactored code and added inline documentation
  45. * - Slides now have unique URL's
  46. * - A basic API to invoke navigation was added
  47. *
  48. * version 0.3:
  49. * - Added licensing terms
  50. *
  51. * version 0.4:
  52. * - Fixed broken links on touch devices.
  53. *
  54. *
  55. * @author Hakim El Hattab
  56. * @version 0.4
  57. */
  58. var Slideshow = (function(){
  59. var indexh = 0,
  60. indexv = 0;
  61. /**
  62. * Activates the main program logic.
  63. */
  64. function initialize() {
  65. document.addEventListener('keydown', onDocumentKeyDown, false);
  66. document.addEventListener('touchstart', onDocumentTouchStart, false);
  67. window.addEventListener('hashchange', onWindowHashChange, false);
  68. // Read the initial state of the URL (hash)
  69. readURL();
  70. }
  71. /**
  72. * Handler for the document level 'keydown' event.
  73. *
  74. * @param {Object} event
  75. */
  76. function onDocumentKeyDown( event ) {
  77. if( event.keyCode >= 37 && event.keyCode <= 40 ) {
  78. switch( event.keyCode ) {
  79. case 37: navigateLeft(); break; // left
  80. case 39: navigateRight(); break; // right
  81. case 38: navigateUp(); break; // up
  82. case 40: navigateDown(); break; // down
  83. }
  84. slide();
  85. event.preventDefault();
  86. }
  87. }
  88. /**
  89. * Handler for the document level 'touchstart' event.
  90. *
  91. * This enables very basic tap interaction for touch
  92. * devices. Added mainly for performance testing of 3D
  93. * transforms on iOS but was so happily surprised with
  94. * how smoothly it runs so I left it in here. Apple +1
  95. *
  96. * @param {Object} event
  97. */
  98. function onDocumentTouchStart( event ) {
  99. // We're only interested in one point taps
  100. if (event.touches.length === 1) {
  101. // Never prevent taps on anchors and images
  102. if( event.target.tagName.toLowerCase() === 'a' || event.target.tagName.toLowerCase() === 'img' ) {
  103. return;
  104. }
  105. event.preventDefault();
  106. var point = {
  107. x: event.touches[0].clientX,
  108. y: event.touches[0].clientY
  109. };
  110. // Define the extent of the areas that may be tapped
  111. // to navigate
  112. var wt = window.innerWidth * 0.3;
  113. var ht = window.innerHeight * 0.3;
  114. if( point.x < wt ) {
  115. navigateLeft();
  116. }
  117. else if( point.x > window.innerWidth - wt ) {
  118. navigateRight();
  119. }
  120. else if( point.y < ht ) {
  121. navigateUp();
  122. }
  123. else if( point.y > window.innerHeight - ht ) {
  124. navigateDown();
  125. }
  126. slide();
  127. }
  128. }
  129. /**
  130. * Handler for the window level 'hashchange' event.
  131. *
  132. * @param {Object} event
  133. */
  134. function onWindowHashChange( event ) {
  135. readURL();
  136. }
  137. /**
  138. * Updates one dimension of slides by showing the slide
  139. * with the specified index.
  140. *
  141. * @param {String} selector A CSS selector that will fetch
  142. * the group of slides we are working with
  143. * @param {Number} index The index of the slide that should be
  144. * shown
  145. *
  146. * @return {Number} The index of the slide that is now shown,
  147. * might differ from the passed in index if it was out of
  148. * bounds.
  149. */
  150. function updateSlides( selector, index ) {
  151. // Select all slides and convert the NodeList result to
  152. // an array
  153. var slides = Array.prototype.slice.call( document.querySelectorAll( selector ) );
  154. if( slides.length ) {
  155. // Enforce max and minimum index bounds
  156. index = Math.max(Math.min(index, slides.length - 1), 0);
  157. slides[index].setAttribute('class', 'present');
  158. // Any element previous to index is given the 'past' class
  159. slides.slice(0, index).map(function(element){
  160. element.setAttribute('class', 'past');
  161. });
  162. // Any element subsequent to index is given the 'future' class
  163. slides.slice(index + 1).map(function(element){
  164. element.setAttribute('class', 'future');
  165. });
  166. }
  167. else {
  168. // Since there are no slides we can't be anywhere beyond the
  169. // zeroth index
  170. index = 0;
  171. }
  172. return index;
  173. }
  174. /**
  175. * Updates the visual slides to represent the currently
  176. * set indices.
  177. */
  178. function slide() {
  179. indexh = updateSlides( '#main>section', indexh );
  180. indexv = updateSlides( 'section.present>section', indexv );
  181. writeURL();
  182. }
  183. /**
  184. * Reads the current URL (hash) and navigates accordingly.
  185. */
  186. function readURL() {
  187. // Break the hash down to separate components
  188. var bits = window.location.hash.slice(2).split('/');
  189. // Read the index components of the hash
  190. indexh = bits[0] ? parseInt( bits[0] ) : 0;
  191. indexv = bits[1] ? parseInt( bits[1] ) : 0;
  192. navigateTo( indexh, indexv );
  193. }
  194. /**
  195. * Updates the page URL (hash) to reflect the current
  196. * navigational state.
  197. */
  198. function writeURL() {
  199. var url = '/';
  200. // Only include the minimum possible number of components in
  201. // the URL
  202. if( indexh > 0 || indexv > 0 ) url += indexh
  203. if( indexv > 0 ) url += '/' + indexv
  204. window.location.hash = url;
  205. }
  206. /**
  207. * Triggers a navigation to the specified indices.
  208. *
  209. * @param {Number} h The horizontal index of the slide to show
  210. * @param {Number} v The vertical index of the slide to show
  211. */
  212. function navigateTo( h, v ) {
  213. indexh = h === undefined ? indexh : h;
  214. indexv = v === undefined ? indexv : v;
  215. slide();
  216. }
  217. function navigateLeft() {
  218. indexh --;
  219. indexv = 0;
  220. slide();
  221. }
  222. function navigateRight() {
  223. indexh ++;
  224. indexv = 0;
  225. slide();
  226. }
  227. function navigateUp() {
  228. indexv --;
  229. slide();
  230. }
  231. function navigateDown() {
  232. indexv ++;
  233. slide();
  234. }
  235. // Initialize the program. Done right before returning to ensure
  236. // that any inline variable definitions are available to all
  237. // functions
  238. initialize();
  239. // Expose some methods publicly
  240. return {
  241. navigateTo: navigateTo,
  242. navigateLeft: navigateLeft,
  243. navigateRight: navigateRight,
  244. navigateUp: navigateUp,
  245. navigateDown: navigateDown
  246. };
  247. })();