Friday
Feb 6, 2009
10:57 pm
jquery Image Rotator
I had the opportunity to finally get my feet wet with jQuery recently and quite enjoyed the experience. One of the big parts of the site functionality that the designer was looking for was the ability to rotate through a potentially large number of logos, fading in and out from the set in order between three or four “image “slots” on the page.
What I came up with, building heavily on the work of Torsten Baldes and others, is nothing more than building an array of images within a container and then cycling through that collection by swapping items in a second array of image spots. This is the function that performs that work where “elements” is the array of images and “#logoimage”+slot is the id of a div from the list of divs we created based on how many images the user wants to display on the page at one time.
$.imageslide.next = function(container, elements, settings, slot, addelement) { slot = slot + 1; if(slot > settings.count) { slot=1; } addelement = addelement + 1; if (addelement > elements.length-1) { addelement = 0; } if (settings.animationtype == 'slide') { $('#logoimage'+slot).slideUp(settings.speed, function() { $('#logoimage'+slot).empty(); $('#logoimage'+slot).append($(elements[addelement])); }); $('#logoimage'+slot).slideDown(settings.speed); } else if (settings.animationtype == 'fade') { $('#logoimage'+slot).fadeTo(settings.speed, 0, function() { $('#logoimage'+slot).empty(); $('#logoimage'+slot).append($(elements[addelement])); }); $('#logoimage'+slot).fadeTo(settings.speed, 1); } else { alert(settings + 'imageslide-animationtype must either be \'slide\' or \'fade\''); return false; } setTimeout((function() { $.imageslide.next(container, elements, settings, slot, addelement); }), settings.timeout); };
The script is invoked using
<script type="text/javascript"> $(document).ready( function(){ $('#slideImages').imageslide({animationtype: 'fade', speed: 750, timeout: 2000, count: 4 });} ); </script>
and, in this case, addresses a container with an id of “slideImages” that contains a list of images.
You can download the script or see it in action if you’re so inclined.