This JavaScript code snippet helps you to create a simple image viewer. It shows small thumbnail images that represent larger ones. Clicking a thumbnail displays its full-size version in the main area. It’s great for easily browsing through images without any hassle, especially handy for websites displaying galleries or portfolios.
You can use this code on any website that showcases image galleries or portfolios. It enhances user experience by providing a simple and intuitive way to navigate through images. Additionally, it requires minimal setup and can be easily customized to match your website’s design.
How to Create a Simple JavaScript Image Viewer
1. First, let’s set up the HTML structure for our image viewer. Copy and paste the following code into your HTML file:
<img src="https://source.unsplash.com/ufFIweqSPd4/800x800" id="main"> <div id="thumbnails"> <img src="https://source.unsplash.com/ufFIweqSPd4/800x800"> <img src="https://source.unsplash.com/O0uCm1WLnA0/800x800"> <img src="https://source.unsplash.com/pV5ckb2HEVk/800x800"> <img src="https://source.unsplash.com/j9QEFAQqaXc/800x800"> <img src="https://source.unsplash.com/EXkbaeN05lY/800x800"> <img src="https://source.unsplash.com/B2mq60Ksrsg/800x800"> </div>
2. Next, let’s add some CSS to style our image viewer. Create a file named styles.css
and add the following styles:
#main, #thumbnails img { box-shadow: 2px 2px 10px 5px #b8b8b8; border-radius: 10px; } * { transition: all 0.5s ease; } #thumbnails { text-align: center; } #thumbnails img { width: 100px; height: 100px; margin: 10px; cursor: pointer; } @media only screen and (max-width: 480px) { #thumbnails img { width: 50px; height: 50px; } } #thumbnails img:hover { transform: scale(1.05); } #main { width: 50%; height: 400px; object-fit: cover; display: block; margin: 20px auto; } @media only screen and (max-width: 480px) { #main { width: 100%; } } .hidden { opacity: 0; }
3. Finally, let’s add JavaScript to make our image viewer interactive. Create a file named script.js
and include the following code:
var thumbnails = document.getElementById("thumbnails") var imgs = thumbnails.getElementsByTagName("img") var main = document.getElementById("main") var counter=0; for(let i=0;i<imgs.length;i++){ let img=imgs[i] img.addEventListener("click",function(){ main.src=this.src }) }
Feel free to customize the HTML, CSS, and JavaScript code to match the design and functionality requirements of your website. You can adjust styles, add animations, or incorporate additional features as needed.
That’s all! hopefully, you have successfully created a simple image viewer on your website. If you have any questions or suggestions, feel free to comment below.