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.


Demo

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.



preview
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>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
<style>
.preview {
width:640px;
height:360px}

.thumb {
width:205px;
margin-right:3px;}

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

.selected {
border:3px solid #ff0000;}
</style>
</head>
<body>
<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)"/>
<script>

    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 = img.id
    }
</script>
</body>
</html>

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

Recommended Books & Training Resources

Professional JavaScript for Web Developers JavaScript and jQuery: The Missing Manual Murachs JavaScript and DOM Scripting