Chapter Three LLC

Simple jQuery Tricks: Flipping Through A List

Josh Koenig

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();
        count++;
        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.

Enjoy!

ehh

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..

Posted by Virgil Spruit (not verified) | Sep. 15th, 2008 @ 6:34am | Link to this Comment

thanks for the great

thanks for the great rosources, very usefully for me :)
Thanks for sharing it,

Werbeagentur

Posted by Werbeagentur (not verified) | Dec. 25th, 2007 @ 5:32am | Link to this Comment

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <br> <br/> <br /> <p> <img> <blockquote> <i> <b> <u>
  • Lines and paragraphs break automatically.
  • SmartyPants will translate ASCII punctuation characters into “smart” typographic punctuation HTML entities.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options