Hi there. I’m learning jQuery and finding it super easy and fun to work with!
Here’s a simple fade-in/out slideshow I wrote for a friend’s website. I knew there were already plug-ins out there for achieving this sort of thing, but I decided to write my own in order to become more familiar with some of the basic concepts.
See it in action. Here’s the HTML we’re outputting:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <div class="slideshow"> <div> <img src="1.jpg" alt="Image One" /> <p class="controls"><a href="#2" class="next">Next</a></p> </div> <div> <img src="2.jpg" alt="Image Two" /> <p class="controls"><a href="#1" class="prev">Prev</a> / <a href="#3" class="next">Next</a></p> </div> <div> <img src="3.jpg" alt="Image Three" /> <p class="controls"><a href="#2" class="prev">Prev</a></p> </div> </div> |
And here’s the jQuery:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | $(document).ready(function(){ // Set the initial state: Hide all but the first slide $('.slideshow').find('> div:eq(0)').nextAll().css({'opacity':'0','display':'none'}); // On click of a controller link... $('.controls > a').click(function(event) { event.preventDefault(); // Get the div containing the clicked link... var currentslide = $(this).parents('div:first'); // ... and get the index of that div var currentposition = $('.slideshow div').index(currentslide); // Use that index to get the slide we'll be fading to var nextposition = ($(this).attr('class')=='next') ? currentposition+1 : currentposition-1; // Fade the current slide out... $('.slideshow div:eq('+currentposition+')').animate({opacity: 0}, 250, function() { // ... and hide it. $('.slideshow div:eq('+currentposition+')').css('display','none'); // Show the next slide... $('.slideshow div:eq('+nextposition+')').css('display','block'); // ... and fade it in. $('.slideshow div:eq('+nextposition+')').animate({opacity: 100}, 1500); } ); }); }); |
As you can see, it’s pretty basic. There’s a number of improvements that could be made, such as having the jQuery insert the control links as they’re somewhat redundant for the non-JS user. Also, it’s a bit fussy about divs — you might want to have some inside your slides but, as written, that would confuse it. I’ll post again if I get around to addressing that.
As always, best wishes to you in your coding!
Tags: JavaScript, jQuery