jQuery Crossfade Plugin


/ Published in: JavaScript
Save to your folder(s)

This is just a basic jQuery crossfade plugin. Should be executed on a list object (ul or ol) because it does specifically look for the li children. The plugin, as implemented, has two options, speed and pause. Speed being the speed at which the top image fades, and pause being the amount of time between fades.


Copy this code and paste it in your HTML
  1. (function($) {
  2.  
  3. $.fn.dfcrossfade = function(options) {
  4.  
  5. //options, obviously
  6. var defaults = {
  7. speed: 800,
  8. pause: 3000
  9. },
  10.  
  11. options = $.extend(defaults, options);
  12.  
  13. this.each(function() {
  14.  
  15. //grab this item and the list items (children)
  16. //this way, the children are cached and not your
  17. //not constantly selecting the items from the dom
  18. var $this = $(this),
  19. $children = $this.children("li");
  20.  
  21. //set css styling for selected item and the children
  22. $this.css({
  23. 'position' : 'relative',
  24. 'list-style' : 'none',
  25. });
  26.  
  27. $children.css({
  28. 'position' : 'absolute',
  29. 'left' : 0,
  30. 'z-index' : 0
  31. });
  32.  
  33. var $first = $children.eq(0), //grab first element (top item)
  34. $next, //initalize variable to hold the next item
  35. length = $children.length, //determine length of the array
  36. index = 0; //initialize an index variable
  37.  
  38. //set z-index of the first item to 2, above all others
  39. //because all others are 0
  40. $first.css({ 'z-index' : 2 });
  41.  
  42. //start yor timer
  43. var timer = window.setInterval(function() {
  44.  
  45. //determine if your at the end of the array
  46. //if so, set index to the first item
  47. //otherwise, increment to the next index
  48. if (!$children.eq(index+1).length) { index = 0; }
  49. else { index++; }
  50.  
  51. //grab the next item
  52. $next = $children.eq(index);
  53.  
  54. //set z-index for the next item so that it is, one above all other elements
  55. //but one under the top item
  56. $next.css({ 'z-index': 1 });
  57.  
  58. //fade the top item out, revealing the next item
  59. $first.fadeTo(options.speed, 0, function() {
  60.  
  61. //then just set the z-index to the lower level
  62. //and fade it back in
  63. $first.css({ 'z-index' : 0 }).fadeTo(0,1);
  64.  
  65. //set the next, now the top, item to the top level
  66. $next.css({ 'z-index' : 2 });
  67.  
  68. //make the new top item, $first
  69. $first = $next;
  70. });
  71.  
  72. }, options.pause);
  73.  
  74. });
  75.  
  76. return this;
  77.  
  78. };
  79.  
  80. })(jQuery);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.