4 By Chris Coyier: http://css-tricks.com
5 with major improvements by Doug Neiner: http://pixelgraphics.us/
6 based on work by Remy Sharp: http://jqueryfordesigners.com/
8 To use the navigationFormatter function, you must have a function that
9 accepts two paramaters, and returns a string of HTML text.
11 index = integer index (1 based);
12 panel = jQuery wrapped LI item this tab references
13 @return = Must return a string of HTML/Text
15 navigationFormatter: function(index, panel){
16 return "Panel #" + index; // This would have each tab with the text 'Panel #X' where X = index
22 $.anythingSlider = function(el, options) {
24 // To avoid scope issues, use 'base' instead of 'this'
25 // to reference this class from internal events and functions.
28 // Wraps the ul in the necessary divs and then gives Access to jQuery element
29 base.$el = $(el).addClass('anythingBase').wrap('<div class="anythingSlider"><div class="anythingWindow" /></div>');
31 // Add a reverse reference to the DOM object
32 base.$el.data("AnythingSlider", base);
34 base.init = function(){
36 base.options = $.extend({}, $.anythingSlider.defaults, options);
38 // Cache existing DOM elements for later
39 // base.$el = original ul
40 // for wrap - get parent() then closest in case the ul has "anythingSlider" class
41 base.$wrapper = base.$el.parent().closest('div.anythingSlider').addClass('anythingSlider-' + base.options.theme);
42 base.$window = base.$el.closest('div.anythingWindow');
43 base.$controls = $('<div class="anythingControls"></div>').appendTo(base.$wrapper);
44 base.$items = base.$el.find('> li').addClass('panel');
46 // Set up a few defaults & get details
47 base.pages = base.$items.length;
48 base.timer = null; // slideshow timer (setInterval) container
49 base.flag = false; // event flag to prevent multiple calls (used in control click/focusin)
50 base.playing = false; // slideshow state
51 base.hovered = false; // actively hovering over the slider
52 base.panelSize = []; // will contain dimensions and left position of each panel
53 base.currentPage = base.options.startPanel;
54 base.hasEmb = !!base.$items.find('embed[src*=youtube]').length; // embedded youtube objects exist in the slider
55 base.hasSwfo = (typeof(swfobject) !== 'undefined' && swfobject.hasOwnProperty('embedSWF') && $.isFunction(swfobject.embedSWF)) ? true : false; // is swfobject loaded?
57 // Get index (run time) of this slider on the page
58 base.runTimes = $('div.anythingSlider').index(base.$wrapper) + 1;
60 // Make sure easing function exists.
61 if (!$.isFunction($.easing[base.options.easing])) { base.options.easing = "swing"; }
63 // Add theme stylesheet, if it isn't already loaded
64 if (base.options.theme != 'default' && !$('link[href*=' + base.options.theme + ']').length){
65 $('body').append('<link rel="stylesheet" href="' + base.options.themeDirectory.replace(/\{themeName\}/g, base.options.theme) + '" type="text/css" />');
68 // Initialize YouTube javascript api, if YouTube video is present
69 if (base.hasEmb && base.hasSwfo) {
70 base.$items.find('embed[src*=youtube]').each(function(i){
71 // Older IE doesn't have an object - just make sure we are wrapping the correct element
72 var $tar = ($(this).parent()[0].tagName == "OBJECT") ? $(this).parent() : $(this);
73 $tar.wrap('<div id="ytvideo' + i + '"></div>');
74 // use SWFObject if it exists, it replaces the wrapper with the object/embed
75 swfobject.embedSWF($(this).attr('src') + '&enablejsapi=1&version=3&playerapiid=ytvideo' + i, 'ytvideo' + i, '100%', '100%', '10', null, null, { allowScriptAccess: "always", wmode : base.options.addWmodeToObject }, {});
78 /***** Consider removing this portion completely, if users will use SWFObject *****
79 // This commented out code will allow YouTube API functions to work for non-IE browsers
80 else if (base.hasEmb) {
81 // initialize youtube api when swf isn't loaded - doesn't work in IE (even if you find('embed'))
82 base.$items.find('object').each(function(i){
83 if ($(this).find('[src*=youtube]').length){
85 .prepend('<param name="wmode" value="' + base.options.addWmodeToObject +'"/>')
86 .wrap('<div id="yt-temp"></div>')
87 .find('embed[src*=youtube]').attr('src', function(j,s){ return s + '&enablejsapi=1&version=3&playerapiid=ytvideo' + i; })
88 .attr('wmode',base.options.addWmodeToObject).end()
89 .find('param[value*=youtube]').attr('value', function(j,v){ return v + '&enablejsapi=1&version=3&playerapiid=ytvideo' + i; }).end()
90 // detach/appendTo required to initialize the wmode code
92 .appendTo($('#yt-temp'))
93 .attr('id', 'ytvideo' + i)
98 } // ***** End script removal consideration *****/
100 // Set the dimensions
101 if (base.options.resizeContents) {
102 if (base.options.width) { base.$wrapper.add(base.$items).css('width', base.options.width); }
103 if (base.options.height) { base.$wrapper.add(base.$items).css('height', base.options.height); }
104 if (base.hasEmb){ base.$el.find('object, embed').css({ width : '100%', height: '100%' }); } // this only expands youtube videos
107 // Remove navigation & player if there is only one page
108 if (base.pages === 1) {
109 base.options.autoPlay = false;
110 base.options.buildNavigation = false;
111 base.options.buildArrows = false;
114 // If autoPlay functionality is included, then initialize the settings
115 if (base.options.autoPlay) {
116 base.playing = !base.options.startStopped; // Sets the playing variable to false if startStopped is true
117 base.buildAutoPlay();
120 // Build the navigation
121 base.buildNavigation();
123 // Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
124 // This supports the "infinite" scrolling, also ensures any cloned elements don't duplicate an ID
125 base.$el.prepend( base.$items.filter(':last').clone().addClass('cloned').removeAttr('id') );
126 base.$el.append( base.$items.filter(':first').clone().addClass('cloned').removeAttr('id') );
128 // We just added two items, time to re-cache the list, then get the dimensions of each panel
129 base.$items = base.$el.find('> li');
130 base.setDimensions();
131 if (!base.options.resizeContents) { $(window).load(function(){ base.setDimensions(); }); } // set dimensions after all images load
133 // Build forwards/backwards buttons
134 if (base.options.buildArrows) { base.buildNextBackButtons(); }
136 // If pauseOnHover then add hover effects
137 if (base.options.pauseOnHover) {
138 base.$wrapper.hover(function() {
140 base.$el.trigger('slideshow_paused', base);
141 if ($.isFunction(base.options.onShowPause)) { base.options.onShowPause(base); }
142 base.clearTimer(true);
146 base.$el.trigger('slideshow_unpaused', base);
147 if ($.isFunction(base.options.onShowUnpause)) { base.options.onShowUnpause(base); }
148 base.startStop(base.playing, true);
153 // If a hash can not be used to trigger the plugin, then go to start panel
154 if ((base.options.hashTags === true && !base.gotoHash()) || base.options.hashTags === false) {
155 base.setCurrentPage(base.options.startPanel, false);
158 // Fix tabbing through the page
159 base.$items.find('a').focus(function(){
160 base.$items.find('.focusedLink').removeClass('focusedLink');
161 $(this).addClass('focusedLink');
162 base.$items.each(function(i){
163 if ($(this).find('a.focusedLink').length) {
170 // Hide/Show navigation & play/stop controls
171 base.slideControls(false);
172 base.$wrapper.hover(function(e){
173 base.hovered = (e.type=="mouseenter") ? true : false;
174 base.slideControls( base.hovered, false );
177 // Add keyboard navigation
178 $(document).keyup(function(e){
179 if (base.$wrapper.is('.activeSlider')) {
181 case 39: // right arrow
184 case 37: //left arrow
193 // Creates the numbered navigation links
194 base.buildNavigation = function() {
195 base.$nav = $('<ul class="thumbNav" />').appendTo(base.$controls);
196 if (base.options.playRtl) { base.$wrapper.addClass('rtl'); }
198 if (base.options.buildNavigation && (base.pages > 1)) {
199 base.$items.each(function(i,el) {
201 $a = $("<a href='#'></a>").addClass('panel' + index).wrap("<li />");
202 base.$nav.append($a.parent()); // use $a.parent() so IE will add <li> instead of only the <a> to the <ul>
204 // If a formatter function is present, use it
205 if ($.isFunction(base.options.navigationFormatter)) {
206 var tmp = base.options.navigationFormatter(index, $(this));
208 // Add formatting to title attribute if text is hidden
209 if (parseInt($a.css('text-indent'),10) < 0) { $a.addClass(base.options.tooltipClass).attr('title', tmp); }
214 $a.bind(base.options.clickControls, function(e) {
216 // prevent running functions twice (once for click, second time for focusin)
217 base.flag = true; setTimeout(function(){ base.flag = false; }, 100);
218 base.gotoPage(index);
219 if (base.options.hashTags) { base.setHash('panel' + base.runTimes + '-' + index); }
229 // Creates the Forward/Backward buttons
230 base.buildNextBackButtons = function() {
231 base.$forward = $('<span class="arrow forward"><a href="#">' + base.options.forwardText + '</a></span>');
232 base.$back = $('<span class="arrow back"><a href="#">' + base.options.backText + '</a></span>');
234 // Bind to the forward and back buttons
235 base.$back.bind(base.options.clickArrows, function(e) {
239 base.$forward.bind(base.options.clickArrows, function(e) {
243 // using tab to get to arrow links will show they have focus (outline is disabled in css)
244 base.$back.add(base.$forward).find('a').bind('focusin focusout',function(){
245 $(this).toggleClass('hover');
248 // Append elements to page
249 base.$wrapper.prepend(base.$forward).prepend(base.$back);
250 base.$arrowWidth = base.$forward.width();
253 // Creates the Start/Stop button
254 base.buildAutoPlay = function(){
255 base.$startStop = $("<a href='#' class='start-stop'></a>").html(base.playing ? base.options.stopText : base.options.startText);
256 base.$controls.append(base.$startStop);
258 .bind(base.options.clickSlideshow, function(e) {
259 base.startStop(!base.playing);
261 if (base.options.playRtl) {
264 base.goForward(true);
269 // show button has focus while tabbing
270 .bind('focusin focusout',function(){
271 $(this).toggleClass('hover');
274 // Use the same setting, but trigger the start;
275 base.startStop(base.playing);
278 // Set panel dimensions to either resize content or adjust panel to content
279 base.setDimensions = function(){
280 var w, h, c, cw, dw, leftEdge = 0, bww = base.$window.width(), winw = $(window).width();
281 base.$items.each(function(i){
282 c = $(this).children('*');
283 if (base.options.resizeContents){
284 // get viewport width & height from options (if set), or css
285 w = parseInt(base.options.width,10) || bww;
286 h = parseInt(base.options.height,10) || base.$window.height();
288 $(this).css({ width: w, height: h });
289 // resize panel contents, if solitary (wrapped content or solitary image)
290 if (c.length == 1){ c.css({ width: '100%', height: '100%' }); }
292 // get panel width & height and save it
293 w = $(this).width(); // if not defined, it will return the width of the ul parent
294 dw = (w >= winw) ? true : false; // width defined from css?
295 if (c.length == 1 && dw){
296 cw = (c.width() >= winw) ? bww : c.width(); // get width of solitary child
297 $(this).css('width', cw); // set width of panel
298 c.css('max-width', cw); // set max width for all children
301 w = (dw) ? base.options.width || bww : w;
302 $(this).css('width', w);
303 h = $(this).outerHeight(); // get height after setting width
304 $(this).css('height', h);
306 base.panelSize[i] = [w,h,leftEdge];
309 // Set total width of slider, but don't go beyond the set max overall width (limited by Opera)
310 base.$el.css('width', (leftEdge < base.options.maxOverallWidth) ? leftEdge : base.options.maxOverallWidth);
313 base.gotoPage = function(page, autoplay) {
314 if (typeof(page) === "undefined" || page === null) {
315 page = base.options.startPage;
316 base.setCurrentPage(base.options.startPage);
319 // pause YouTube videos before scrolling or prevent change if playing
320 if (base.checkVideo(base.playing)) { return; }
322 base.$el.trigger('slide_init', base);
323 if ($.isFunction(base.options.onSlideInit)) { base.options.onSlideInit(base); }
325 base.slideControls(true, false);
327 // Just check for bounds
328 if (page > base.pages + 1) { page = base.pages; }
329 if (page < 0 ) { page = 1; }
331 // When autoplay isn't passed, we stop the timer
332 if (autoplay !== true) { autoplay = false; }
333 // Stop the slider when we reach the last page, if the option stopAtEnd is set to true
334 if (!autoplay || (base.options.stopAtEnd && page == base.pages)) { base.startStop(false); }
336 base.$el.trigger('slide_begin', base);
337 if ($.isFunction(base.options.onSlideBegin)) { base.options.onSlideBegin(base); }
339 // resize slider if content size varies
340 if (!base.options.resizeContents) {
341 // animating the wrapper resize before the window prevents flickering in Firefox
342 base.$wrapper.filter(':not(:animated)').animate(
343 { width: base.panelSize[page][0], height: base.panelSize[page][1] },
344 { queue: false, duration: base.options.animationTime, easing: base.options.easing }
348 base.$window.filter(':not(:animated)').animate(
349 { scrollLeft : base.panelSize[page][2] },
350 { queue: false, duration: base.options.animationTime, easing: base.options.easing, complete: function(){ base.endAnimation(page); } }
355 base.endAnimation = function(page){
357 base.$window.scrollLeft(base.panelSize[base.pages][2]);
359 } else if (page > base.pages) {
360 // reset back to start position
361 base.$window.scrollLeft(base.panelSize[1][2]);
364 base.setCurrentPage(page, false);
366 if (!base.hovered) { base.slideControls(false); }
368 // continue YouTube video if in current panel
370 var emb = base.$items.eq(base.currentPage).find('object[id*=ytvideo], embed[id*=ytvideo]');
371 // player states: unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5).
372 if (emb.length && $.isFunction(emb[0].getPlayerState) && emb[0].getPlayerState() > 0 && emb[0].getPlayerState() != 5) {
377 base.$el.trigger('slide_complete', base);
378 if ($.isFunction(base.options.onSlideComplete)) {
379 // Added setTimeout (zero time) to ensure animation is complete... for some reason this code:
380 // alert(base.$window.is(':animated')); // alerts true - http://dev.jquery.com/ticket/7156
381 setTimeout(function(){ base.options.onSlideComplete(base); }, 0);
385 base.setCurrentPage = function(page, move) {
387 if (base.options.buildNavigation){
388 base.$nav.find('.cur').removeClass('cur');
389 base.$nav.find('a').eq(page - 1).addClass('cur');
392 // Only change left if move does not equal false
395 width: base.panelSize[page][0],
396 height: base.panelSize[page][1]
398 base.$wrapper.scrollLeft(0); // reset in case tabbing changed this scrollLeft
399 base.$window.scrollLeft( base.panelSize[page][2] );
401 // Update local variable
402 base.currentPage = page;
404 // Set current slider as active so keyboard navigation works properly
405 if (!base.$wrapper.is('.activeSlider')){
406 $('.activeSlider').removeClass('activeSlider');
407 base.$wrapper.addClass('activeSlider');
411 base.goForward = function(autoplay) {
412 if (autoplay !== true) { autoplay = false; base.startStop(false); }
413 base.gotoPage(base.currentPage + 1, autoplay);
416 base.goBack = function(autoplay) {
417 if (autoplay !== true) { autoplay = false; base.startStop(false); }
418 base.gotoPage(base.currentPage - 1, autoplay);
421 // This method tries to find a hash that matches panel-X
422 // If found, it tries to find a matching item
423 // If that is found as well, then that item starts visible
424 base.gotoHash = function(){
425 var hash = window.location.hash.match(/^#?panel(\d+)-(\d+)$/);
427 var panel = parseInt(hash[1],10);
428 if (panel == base.runTimes) {
429 var slide = parseInt(hash[2],10),
430 $item = base.$items.filter(':eq(' + slide + ')');
431 if ($item.length !== 0) {
432 base.setCurrentPage(slide, false);
437 return false; // An item wasn't found;
440 // Taken from AJAXY jquery.history Plugin
441 base.setHash = function (hash){
443 if ( typeof window.location.hash !== 'undefined' ) {
444 if ( window.location.hash !== hash ) {
445 window.location.hash = hash;
447 } else if ( location.hash !== hash ) {
448 location.hash = hash;
454 // <-- End AJAXY code
456 // Slide controls (nav and play/stop button up or down)
457 base.slideControls = function(toggle, playing){
458 var dir = (toggle) ? 'slideDown' : 'slideUp',
459 t1 = (toggle) ? 0 : base.options.animationTime,
460 t2 = (toggle) ? base.options.animationTime: 0,
461 sign = (toggle) ? 0 : 1; // 0 = visible, 1 = hidden
462 if (base.options.toggleControls) {
463 base.$controls.stop(true,true).delay(t1)[dir](base.options.animationTime/2).delay(t2);
465 if (base.options.toggleArrows) {
466 if (!base.hovered && base.playing) { sign = 1; }
467 base.$forward.stop(true,true).delay(t1).animate({ right: sign * base.$arrowWidth, opacity: t2 }, base.options.animationTime/2);
468 base.$back.stop(true,true).delay(t1).animate({ left: sign * base.$arrowWidth, opacity: t2 }, base.options.animationTime/2);
472 base.clearTimer = function(paused){
473 // Clear the timer only if it is set
475 window.clearInterval(base.timer);
477 base.$el.trigger('slideshow_stop', base);
478 if ($.isFunction(base.options.onShowStop)) { base.options.onShowStop(base); }
483 // Handles stopping and playing the slideshow
484 // Pass startStop(false) to stop and startStop(true) to play
485 base.startStop = function(playing, paused) {
486 if (playing !== true) { playing = false; } // Default if not supplied is false
488 if (playing && !paused) {
489 base.$el.trigger('slideshow_start', base);
490 if ($.isFunction(base.options.onShowStart)) { base.options.onShowStart(base); }
494 base.playing = playing;
496 // Toggle playing and text
497 if (base.options.autoPlay) {
498 base.$startStop.toggleClass('playing', playing).html( playing ? base.options.stopText : base.options.startText );
499 // add button text to title attribute if it is hidden by text-indent
500 if (parseInt(base.$startStop.css('text-indent'),10) < 0) {
501 base.$startStop.addClass(base.options.tooltipClass).attr('title', playing ? 'Stop' : 'Start');
506 base.clearTimer(true); // Just in case this was triggered twice in a row
507 base.timer = window.setInterval(function() {
508 // prevent autoplay if video is playing
509 if (!base.checkVideo(playing)) {
510 if (base.options.playRtl) {
513 base.goForward(true);
516 }, base.options.delay);
522 base.checkVideo = function(playing){
523 // pause YouTube videos before scrolling?
524 var emb, ps, stopAdvance = false;
526 base.$items.find('object[id*=ytvideo], embed[id*=ytvideo]').each(function(){ // include embed for IE; if not using SWFObject, old detach/append code needs "object embed" here
528 if (emb.length && $.isFunction(emb[0].getPlayerState)) {
529 // player states: unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5).
530 ps = emb[0].getPlayerState();
531 // if autoplay, video playing, video is in current panel and resume option are true, then don't advance
532 if (playing && (ps == 1 || ps > 2) && base.$items.index(emb.closest('li.panel')) == base.currentPage && base.options.resumeOnVideoEnd) {
535 // pause video if not autoplaying (if already initialized)
536 if (ps > 0) { emb[0].pauseVideo(); }
544 // Trigger the initialization
548 $.anythingSlider.defaults = {
550 width : null, // Override the default CSS width
551 height : null, // Override the default CSS height
552 resizeContents : true, // If true, solitary images/objects in the panel will expand to fit the viewport
553 tooltipClass : 'tooltip', // Class added to navigation & start/stop button (text copied to title if it is hidden by a negative text indent)
554 theme : 'default', // Theme name
555 themeDirectory : 'css/theme-{themeName}.css', // Theme directory & filename {themeName} is replaced by the theme value above
558 startPanel : 1, // This sets the initial panel
559 hashTags : true, // Should links change the hashtag in the URL?
560 buildArrows : true, // If true, builds the forwards and backwards buttons
561 toggleArrows : false, // If true, side navigation arrows will slide out on hovering & hide @ other times
562 buildNavigation : true, // If true, builds a list of anchor links to link to each panel
563 toggleControls : false, // if true, slide in controls (navigation + play/stop button) on hover and slide change, hide @ other times
564 navigationFormatter : null, // Details at the top of the file on this use (advanced use)
565 forwardText : "»", // Link text used to move the slider forward (hidden by CSS, replaced with arrow image)
566 backText : "«", // Link text used to move the slider back (hidden by CSS, replace with arrow image)
569 autoPlay : true, // This turns off the entire slideshow FUNCTIONALY, not just if it starts running or not
570 startStopped : false, // If autoPlay is on, this can force it to start stopped
571 pauseOnHover : true, // If true & the slideshow is active, the slideshow will pause on hover
572 resumeOnVideoEnd : true, // If true & the slideshow is active & a youtube video is playing, it will pause the autoplay until the video is complete
573 stopAtEnd : false, // If true & the slideshow is active, the slideshow will stop on the last page
574 playRtl : false, // If true, the slideshow will move right-to-left
575 startText : "Start", // Start button text
576 stopText : "Stop", // Stop button text
577 delay : 3000, // How long between slideshow transitions in AutoPlay mode (in milliseconds)
578 animationTime : 600, // How long the slideshow transition takes (in milliseconds)
579 easing : "swing", // Anything other than "linear" or "swing" requires the easing plugin
582 onShowStart : null, // Callback on slideshow start
583 onShowStop : null, // Callback after slideshow stops
584 onShowPause : null, // Callback when slideshow pauses
585 onShowUnpause : null, // Callback when slideshow unpauses - may not trigger properly if user clicks on any controls
586 onSlideInit : null, // Callback when slide initiates, before control animation
587 onSlideBegin : null, // Callback before slide animates
588 onSlideComplete : null, // Callback when slide completes
591 clickArrows : "click", // Event used to activate arrow functionality (e.g. "click" or "mouseenter")
592 clickControls : "click focusin", // Events used to activate navigation control functionality
593 clickSlideshow : "click", // Event used to activate slideshow play/stop button
596 addWmodeToObject : "opaque", // If your slider has an embedded object, the script will automatically add a wmode parameter with this setting
597 maxOverallWidth : 32766 // Max width (in pixels) of combined sliders (side-to-side); set to 32766 to prevent problems with Opera
600 $.fn.anythingSlider = function(options) {
602 // initialize the slider
603 if ((typeof(options)).match('object|undefined')){
604 return this.each(function(i){
605 if ($(this).is('.anythingBase')) { return; } // prevent multiple initializations
606 (new $.anythingSlider(this, options));
609 // If options is a number, process as an external link to page #: $(element).anythingSlider(#)
610 } else if (/\d/.test(options) && !isNaN(options)) {
611 return this.each(function(i) {
612 var anySlide = $(this).data('AnythingSlider');
614 var page = (typeof(options) == "number") ? options : parseInt($.trim(options),10); // accepts " 2 "
615 // ignore out of bound pages
616 if ( page < 1 || page > anySlide.pages ) { return; }
617 anySlide.gotoPage(page);