Simple jQuery Tricks: Flipping Through A List

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();
      $(".myclass li:first-child").show();
      var total = $(".myclass li").size();
      var count = 0;
      $(".mylink a").click( function() {
        $(".myclass li:nth-child("+count+")").hide();
        if (count == total) {
          count = 0;
        $(".myclass li:nth-child("+count+")").show();
        return false;


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.