Simple JavaScript Image Thumbnail Viewer

Thursday, January 10, 2013

If you perform a search on the Internet using any search engine, you will find a countless number of Javascript/jQuery image galleries that are available for you to use in your web projects. However, most of them may be more than what you really need. They may include fancy sliders, pop-up windows, and other cool features. In this tutorial, we are going to cover how to build a simple thumbnail viewer using JavaScript. We are not going to include a lot of bells and whistles. This simple design is intended to be used for projects that require a simple solution.


In this demonstration, as you move the mouse over the thumbnail images, the preview image is updated with the image that is currently hovered (onmouseover event) over. You will also notice that the border around the thumbnail is changed as well. While this demo is designed to swap the image while hovering over the thumbnails, it can be easily reconfigured to use the mouse click (onclick event) as well.

mountains desert highway

HTML, CSS, and JavaScript Code

As previously mentioned, the image in the "preview window" is changed as your mouse moves over the thumbnail images. If you prefer to have the preview image updated when the mouse is clicked, simple change the "onmouseover" event to "onclick". So for example, onmouseover="preview(this)" will be changed to "onclick="preview(this)".

<!DOCTYPE html>
<meta charset="utf-8" />
.preview {

.thumb {

.normal {
border:3px solid #000000;}

.selected {
border:3px solid #ff0000;}
<img id="0" class="preview normal" src="" alt="preview" /><br />
<img id="1" class="thumb normal" src="images/mountains.jpg" alt="mountains" onmouseover="preview(this)"/>
<img id="2" class="thumb normal" src="images/desert.jpg" alt="desert" onmouseover="preview(this)"/>
<img id="3" class="thumb normal" src="images/highway.jpg" alt="highway" onmouseover="preview(this)"/>

    var lastImg = 1; //Set initial thumbnail and preview
    document.getElementById(0).src = document.getElementById(lastImg).src;
    document.getElementById(lastImg).className = "thumb selected";

    function preview(img) {
        document.getElementById(lastImg).className = "thumb normal";
        img.className = "thumb selected";
        document.getElementById(0).src = img.src;
        lastImg =

Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

JavaScript and jQuery: The Missing Manual HTML CSS and JavaScript Editor Murachs JavaScript and DOM Scripting