A simple jQuery gallery

Update: I have improved this functionality and turned it into a jQuery plug-in over on Github: simpleGal

Image galleries are all over the web and the style of gallery we are going to look at here is a fairly popular one. As before, this is something that I have seen people use plug-ins for and whilst those plug-ins might be very powerful and flexible, they are too much for such a simple task.

Mark-up first

Of course we’re going to start with the mark-up. I have opted for a simple unordered list of thumbnails which link to larger versions of themselves. I have called this list thumbnails:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<ul id="thumbnails">
  <li>
    <a href="img/img-01.jpg">
      <img src="img/img-01-tn.jpg" alt="First image" />
    </a>
  </li>
  <li>
    <a href="img/img-02.jpg">
      <img src="img/img-02-tn.jpg" alt="Second image" />
    </a>
  </li>
  <li>
    <a href="img/img-03.jpg">
      <img src="img/img-03-tn.jpg" alt="Third image" />
    </a>
  </li>
</ul>

Now we want somewhere for the main image to display. For this I have created a div with the imaginative id of main-image:

1
2
3
<div id="main-image">
  <img src="img/img-01.jpg" alt="Placeholder image" />
</div>

Now for the fun stuff

That’s all the mark-up we need for this example, so now its time to move on to the jQuery already. The only thing to remember is that you should link to a copy of the jQuery library before you add the code in this next section.

OK, here’s the code we need. (The comments should explain what is happening):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$(document).ready(function() {

  // Adds an 'onclick' even to the links in the thumbnails list
  $('#thumbnails a').click(function () {

    // Sets a variable using the link location
    var galleryImage = $(this).attr('href');

    // Replaces the 'src' attribute of the main image with the URL
    // of the link that has been clicked
    $('#main-image img').attr('src', galleryImage);

    // Stops the default behaviour of the link
    return false;
  });
});

And that’s all there is to it. Enjoy!