marse
marse

Reputation: 873

How to change an image every 15 seconds in HTML

I have an image in my HTML page, and I would like it to change to a different image every 15 seconds.

<img src="img/img 1.jpg" alt="image">

In my local folder img, I have two images which are img 1.jpg and img 2.jpg. How do I change the img 1.jpg to img 2.jpg after 15 seconds?

Upvotes: 1

Views: 3028

Answers (4)

J Santosh
J Santosh

Reputation: 3847

Try this (pure JS)

var myArray = ['img1', 'img2', 'img3', 'img4', 'img5', 'img6']

var count = 0;
setInterval(function() {
  //use this below line if you want random images
  //var rand = myArray[Math.floor(Math.random() * myArray.length)];

  if (count >= myArray.length) count = 0; // if it is last image then show the first image.
  // use this below line if you want images in order.
  var rand = myArray[count];
  document.getElementById('img').src = rand;
  document.getElementById('img').alt = rand; // use 'alt' to display the image name if image is not found
  count++;
}, 1000); // 1000 = 1 second
<img src="img/img 1.jpg" alt="image" id='img' />

Upvotes: 3

Chilli
Chilli

Reputation: 123

Try it:

$(document).ready(function(){

    var img = 0;

    var slides = new Array();

    while (img < 5) {

        img++;

        // put your image src in sequence

        var src = 'assets/images/earth/Sequence' + img + '.jpg';

        slides.push(src);

    }

    var index = 0,timer = 0;

    showNextSlide();

    timer = setInterval(showNextSlide, 15000);

    function showNextSlide() {

        if (index >= slides.length) {

            index = 0;

        }

        document.getElementById('earth').src = slides[index++];
    }

});

Upvotes: 3

Viktor Maksimov
Viktor Maksimov

Reputation: 1465

  1. Firstly include jQuery library in your page.

  2. Then use this script:

    $(document).ready(function() {
        setInterval(function(){
            _path = $('img').attr('src');
            _img_id = _path.replace('img/img', '');
            _img_id = _img_id.replace('.jpg', '');
    
            _img_id++;
    
            if (_img_id == 3) {
                _img_id = 1;
            };
    
            $('img').attr('src', 'img/img' + _img_id + '.jpg');
        }, 15000);
    });
    

Upvotes: 0

user2872777
user2872777

Reputation: 99

To do this, you're going to need some Javascript to change the image. Here is a link to a popular website for help with Javascript, HTML, CSS, and a whole lot more. What you'll want to be looking at specifically though, is the setInterval() function on this page: http://www.w3schools.com/js/js_timing.asp

If you don't know Javascript at all, it is also not a bad place to start learning! If that's all you need it for though, you'll need very little Javascript at all.

Upvotes: 1

Related Questions