Revisiting my jQuery gallery - without jQuery

There’s been a lot of talk lately about The Vanilla Web Diet and not relying on jQuery. This lead to me revisiting some of the code I wrote when I was learning jQuery.

A little over a year ago I published a post on how to make a simple JavaScript gallery. In the spirit of encouraging developers to learn the language behind the library, I’ve written a vanilla JavaScript version.

See the demo →

The HTML

The HTML is really simple. We have one main image and a list of thumbnails, each linking to the full sized image.

1
2
3
4
5
6
7
<img id="main-image" src="img-01.jpg" alt="Placeholder">

<ul id="thumbnails">
  <li><a href="img-01.jpg"><img src="img-01-tn.jpg" alt="Thumbnails"></a></li>
  <li><a href="img-02.jpg"><img src="img-02-tn.jpg" alt="Thumbnails"></a></li>
  <li><a href="img-03.jpg"><img src="img-03-tn.jpg" alt="Thumbnails"></a></li>
</ul>

The JavaScript

The amount of code here is fairly concise, and not that much more than last time. Whats more, it doesn’t require the overhead of the jQuery library.

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

  if (document.querySelectorAll) {

    var links = document.querySelectorAll("#thumbnails a"),
        mainImage = document.getElementById("main-image");

    for (var i=0; i < links.length; i++) {
      links[i].onclick = function (e) {
        e.preventDefault();
        var source = this.getAttribute("href");
        mainImage.setAttribute("src", source);
      };
    }
  }
})();

Now lets step through the code.

Keeping the window object clean

First we wrap our code in a self-executing anonymous function. This keeps our variables from polluting the global scope:

(function () {

})();

Checking for support

Next we’re going to declare the variables we need, but as we’ll be using querySelectorAll, we’re just going to check that the browser supports this before executing our code:

1
2
3
if (document.querySelectorAll) {

}

If the browser doesn’t support querySelectorAll then the browser will skip over the code that follows.

Now we can declare the variables we need. The first will cache all the thumbnail links, and the second will cache the main image:

1
2
var links = document.querySelectorAll("#thumbnails a"),
    mainImage = document.getElementById("main-image");

Switching out the main image

Now we want to loop through all the thumbnails and listen for the click event. When they’re clicked, we change the src attribute of the main image to the thumbnails href value:

1
2
3
4
5
6
7
for (var i=0; i < links.length; i++) {
	links[i].onclick = function (e) {
  	e.preventDefault();
    var source = this.getAttribute("href");
    mainImage.setAttribute("src", source);
  };
}

Improvements?

That’s all there is to it. If theres anything you think could improve this code, I’d love for you to share in the comments or maybe even in your own post.