freddie.bumder
freddie.bumder

Reputation: 15

How To Automatically Change An HTML Image Using JavaScript

NB: I've had a look here for how to change the images on a timer, as oppose to using buttons, but it didn't cater to my code style.

As I'm new to HTML and JS I still don't understand all the aspects and got a little confused on which part they were referring to in translation to how I wrote my code.

CODE:

<!DOCTYPE html>
<html>
  <body>
    <img id="image" src="blank_light.jpg" style="width:100px">
    <p></p>
    <button class="change-image">Change Lights</button>
    <script>
      var imageSources = ["red_light.jpg", "red_and_yellow_light.jpg", "yellow_light.jpg", "green_light.jpg"]
      var buttons = document.getElementsByClassName("change-image")[0];
      var index = 0;

      buttons.addEventListener('click', function() {
        if (index === imageSources.length) {
          index = 0;
        }
        document.getElementById("image").src = imageSources[index];
        index++;
      });

    </script>
  </body>
</html>

I need to remove the buttons and have the images change on a timed basis instead. Ideally every 2 seconds.

Thanks in advance.

Upvotes: 0

Views: 21342

Answers (2)

Jabbi Syed
Jabbi Syed

Reputation: 191

/CoffeeScript
$(document).ready ->
  imageSources = ["image1.jpg", "image2.png", "image3.png", "image4.png", "image5.png"]
  index = 0
  setInterval ( ->
    if index == imageSources.length
      index = 0
    $('#image-test').attr('src', imageSources[index]);
    index++
    return
  ), 2000

Upvotes: 0

Hardik Gondalia
Hardik Gondalia

Reputation: 3717

You need to use setInterval function to change image after every 2 sec

<img id="image" src="blank_light.jpg" style="width:100px">
<p></p>

<script>

var imageSources = ["red_light.jpg", "red_and_yellow_light.jpg", "yellow_light.jpg", "green_light.jpg"]

var index = 0;
setInterval (function(){
  if (index === imageSources.length) {
    index = 0;
  }
  document.getElementById("image").src = imageSources[index];
  index++;
} , 2000);

</script>

CodePen : http://codepen.io/anon/pen/zNWMJK

Upvotes: 8

Related Questions