P'unk Avenue Window

A jQuery progressive enhancement show in just N lines of code, where N is not a big number

March 9th, 2009 by Tom No Comments

I have bigger fish to fry in my Wednesday window blog post, but I wanted to share this snippet.

A simple list of images like this one:

<ul class="slideshow">
<li><img src="wheatpaste_superman.jpg" /></li>
<li><img src="wheats_tidal_wave.jpg" /></li>
<li><img src="who_is_living_in_our_garden.jpg" /></li>
<li><img src="why_we_lost_vietnam.jpg" /></li>
<li><img src="wilmington_traffic_box.jpg" /></li>
<li><img src="wilmington-trestle.jpg" /></li>
<li><img src="witherspoon_building.jpg" /></li>
</ul>

… Can be transformed into a “click for the next image” slideshow with jQuery like so:

<script>
$(function()
{
  $('.slideshow li').hide();
  $('.slideshow li:first').show();
  $('.slideshow li').click(function()
  {
   $(this).hide();
   var next = $(this).next();
   if (!next.length)
   {
    next = $($(this).parent()).children(":first");
   }
   next.show();
  });
});
</script>

If JavaScript is disabled, you simply have all of the images visible instead, which is a reasonable fallback behavior. And your HTML stays sane and meaningful.

jQuery is a beautiful thing.

You can play with a demo here.

Leave a Reply