Simple jQuery Tricks: Flipping Through A List
Navigation : Back to Blog
I (heart) jQuery. The "write less, do more" library has turned me from a javascript hater into a true-believer over the past six months. Not only does it obliterate the pain of cross-browser compatibility issues, it's also so dang elegant and smooth, it makes JS downright fun to work with.
For instance, tonight I had to come up with a way to show a series of images, like a slideshow, with a loop. Basically you run through a list -- seeing one item at a time -- and when you reach the end you see the first item again. There are probably ten or a hundred slideshow applications out there that implement this functionality, but I thought I'd post the short, sweet snippit for the world to make use of:
$(".myclass li").hide();<br /> $(".myclass li:first-child").show();<br /> var total = $(".myclass li").size();<br /> var count = 0;<br /> $(".mylink a").click( function() {<br /> $(".myclass li:nth-child("+count+")").hide();<br /> count++;<br /> if (count == total) {<br /> count = 0;<br /> }<br /> $(".myclass li:nth-child("+count+")").show();<br /> return false;<br /> });Basically you have a list that's got the class "myclass", and then a link with the class "mylink" which click-iterates through the list. If you want to spice it up with some fades or other special effects, it's pretty easy to see how.
This snippit works thanks to jQuery including a nice size() method, and supporting the awesomeness that are CSS3 Selectors. It's hot stuff, and it works, and the applications are endless.
Enjoy!
Comments
Post a comment
Presentations
What we've coded
Videos
Upcoming workshops
-
San Francisco, CAFebruary 28, 2012
-
Denver, COMarch 19, 2012
-
Denver, COMarch 19, 2012






Doesn't the nth-child list start at 1?
var count = 0;
if (count == total)
count = 0;
to...
var count = 1;
if (count > total)
count = 1;
And that made the flipping actually work..
Thank you Josh,
great tutorial. Very helpful...
hey josh,
I am having to do this vertical tabs in drupal! Nice to meet you at drupalcon in Chicago..
Patrick