Computers & ProgrammingFrontend DevelopmentJavaScript

Simple JavaScript Image Thumbnail Viewer

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.

HTML, CSS, and JavaScript Code

The image in the “preview window” can be changed as your mouse moves over the thumbnail images. If you prefer to have the preview image updated when the mouse is clicked, simply 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>

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top