How to create image slider in JavaScript


In this JavaScript tutorial, we are going to create a slider/banner of images that comes one by one. To create a simple slider we don’t need a high-level programming language, we can do this simply by using JavaScript.

Using Array we can define the size and use setInterval to set the time.

JS Snippet
m = new Array(8);

for (i = 0; i < 8; i++) { m[i] = new Image(); m[i].src = "images/pm-modi" + i + ".jpg"; } x = 0; function view() { document.images[0].src = m[x].src; x++; if (x > 7) {
		x = 0;
	}
}
function banner() {
	t = setInterval("view()", "1000");
}

Check the Full example

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            m = new Array(8);

            for (i = 0; i < 8; i++) {
                m[i] = new Image();
                m[i].src = "images/pm-modi" + i + ".jpg";
            }
            x = 0;
            function view() {
                document.images[0].src = m[x].src;
                x++;
                if (x > 7) {
                    x = 0;
                }
            }
            function banner() {
                t = setInterval("view()", "1000");
            }
        </script>

    </head>
    <body onload="banner()">
        <img src="images/pm-modi0.jpg" height=500 width=500>
    </body>
</html>

Similar Posts

About the Author

Websparrow
I like sharing my experiments and ideas with everyone by writing articles on the latest technological trends.