How to Create Image Gallery in JavaScript

Hello Coders, In this blog post, You will learn to create a changeable image gallery in JavaScript. It will be the same as continuously changing images on the Flipkart homepage. Let us learn about it:-

Image gallery in Javascript

In this code, We have used html only to create a div tag to make space for the images to appear on screen. Rest all the work is done with the help of JavaScript. To write JavaScript in HTML we created a script tag in the html file.

 

In that script tag, we created a variable picture that will contain all the images that we want to display on the screen. after that, we will make a function of change image which is also the id of the div tag. In this function, we will upload the picture variable which we made earlier. 

 

After adding that variable we will then set up the time interval to change the picture. We have also used index in this as when the index goes above 2 then it automatically goes to 0 and the process doesn’t stop. 

Code to create Changable Image Gallery in JavScript is:-

<!DOCTYPE html>
<html>

 

<head>
    <title>Image Gallery In javascript</title>
</head>

 

<body>

 

    <div id=“changepic” style=width:900px;
        height:500px;
        border: 2px solid black”>

 

    </div>
    <script type=“text/javascript”>
        var picture = [“https://www.shutterstock.com/image-photo/man-hands-holding-global-network-260nw-1801568002.jpg”, “https://media.gettyimages.com/id/912928582/photo/success.jpg?s=612×612&w=gi&k=20&c=z5O5j4InM9JcwTyHf-lzHhCKsnPoQ-RX7hMN6W87gxQ=”, “https://images.unsplash.com/photo-1682695796954-bad0d0f59ff1?auto=format&fit=crop&q=80&w=1000&ixlib=rb-4.0.3&ixid=M3wxMjA3fDF8MHxlZGl0b3JpYWwtZmVlZHwxNnx8fGVufDB8fHx8fA%3D%3D”, “https://images.pexels.com/photos/1726783/pexels-photo-1726783.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=500&w=1400&dpr=1”];
        // You need to image link or address in this double quotes
        var index = 0;
        function changeimage() {
            document.getElementById(“changepic”).style.backgroundImage = “url(‘” + picture[index] + “‘)”;
            index++;
            if (index > 2) {
                index = 0;
            }
        }
        setInterval(changeimage, 1000);
    </script>

 

</body>

 

</html>

Hope this blog post was helpful to you and you have got the answer to your question. Thank you for visiting our blog. If you have any doubts about any coding questions then let us know in the comments section we will answer them as soon as possible. Till then check out our more blog posts.

Leave a Comment

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