Tuesday, March 11, 2014

Create a image slider sample using JavaScript and HTML5

An image slider is used to slide the images after every few seconds, now a days mostly used  in web designing and development, to attract the user of the website.
In JavaScript, create a simple array and then stores the path of image in that array. By using getElementById("") method we simply change the image using JavaScript.

Code:
 <html>
 <head>
 <script>
 var images = ["images/1.jpg", "images/2.jpg", "images/3.jpg"];
 var imgNum = 0;
 var imgLength = images.length - 1;
 function changeImage(direction) {
     imgNum = imgNum + direction;
     if (imgNum > imgLength) {
         imgNum = 0;
     }
     if (imgNum < 0) {
         imgNum = imgLength;
     }
     document.getElementById('slideshow').src = images[imgNum];
     return false; // prevent default link
 }
 window.setInterval(function() {
     changeImage(1);
 }, 3000);
 </script>
 <style>
img {
width: 800px;
height: 350px;
border-style:solid;
border-width:5px;
border-color:#5695C2;
}
 </style>
 </head>
 <body>
 <center>
 <img src="images/1.jpg" id="slideshow"><br/>
 <a href="#" onclick="return changeImage(-1);">Previous</a><br/>
 <a href="#" onclick="return changeImage(1);">Next</a>
 </center>
 </body>
 </html>

Create a folder and name it and put this .html file inside that and now create a folder inside this and name it images, put all images inside this folder and then rename the image name as defined in the JavaScript code 1.jpg, 2.jpg and 3.jgp.

1 comment: