Change image after given time duration

In some situation you have to be required to change image after given time duration .

Suppose a situation you want to display an ad image on a prticular location and you want that after some time it will replace with the next ad image .

 Check this example link   here display ad on right side after some time

To fulfill this need you need to be just copy the below javascript code and paste it in your file .After minor changement you can use it

<script type="text/javascript">

    (function() {
        var rotator = document.getElementById('rotator');  // change to your image ID
        var imageDir = 'images/';                          // change to your images folder
        var delayInSeconds = 1;                            // set number of seconds delay
      // list image names
        var images = ['1.png', '2.png', '3.png', '4.png'];
        // don't change below this line
        var num = 0;
        var changeImage = function() {
            var len = images.length;
            rotator.src = imageDir + images[num++];
            if (num == len) {
                num = 0;
        setInterval(changeImage, delayInSeconds * 1000);


Now you will need to place an image tag in which you want to display image like below :

<img src="images/1.png" alt="rotating image" width="400" height="300" id="rotator">

Description In the above image tag i give its  id rotator .Now in javascript code you will need to change your image directory path in  var imageDir = 'images/'  variable .Change images with your image directory by given full path , now change after how much time you want to change image in delayInSeconds variable , now next you need to be set your image name in  images = ['1.png', '2.png', '3.png', '4.png'] variable .Change 1.png , 2.png, 3.png, 4.png  with your image name

Please give comment if you have any issue during implementation .

 Happy coding :)

Post a Comment

Previous Post Next Post