Han Hai
Han Hai

Reputation: 11

Changing images periodically in JavaScript

So basically I want to change image in every 5 second, so I wrote the following Javascript code and tag it to html. But the console keep saying that "No javaScript on this page" and the code does not apply

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>JavaScript for Programmers</title>
    </head>
    <body>
        <h2>Mood Change</h2>
        <p>The mood of this web page changes every 5 seconds.</p>
        <p><img id="mood" src="frown.gif" alt="mood"></p>
        <script async src="../scripts/moody.js"></scripts>
    </body>
</html>

  var images=[]
  images[0]="smile.gif";
  images[1]="frown.gif";
  var myMood= document.getElementById("mood");
  function change(){
    if(myMood==images[0]){
      myMood.src=images[1];
    }
    else if(myMood.src==imgaes[1]){
      myMood.src=images[0];
    }
 }

 setInterval(change,5000);      

Upvotes: 0

Views: 2146

Answers (2)

RobG
RobG

Reputation: 147403

The reason your code didn't work is you comparison is in appropriate. Where you have:

var images=[]
  images[0]="smile.gif";
  images[1]="frown.gif";
  var myMood= document.getElementById("mood");

  function change(){
    if (myMood == images[0]) {

then myMood is a DOM element and images[0] is a string. Those two will never almost never be equal (unless the DOM element's toString methods produces exactly the same string).

You probably meant:

    if (myMood.src == images[0]) {

so that you compare two strings that are more likely to be the same.

Upvotes: 0

Roko C. Buljan
Roko C. Buljan

Reputation: 206102

</scripts> should be </script>

Also your JS could look like this: http://jsbin.com/nawono/2/edit

var myMood= document.getElementById("mood");
var images=[
    "smile.gif",
    "frown.gif"
];

function change(){
    myMood.src= images.reverse()[0];
}

setInterval(change,5000); 

Ahh, to explain images.reverse()[0];, it reverses the array order and we always take out the 0 indexed key. Quite nice

Upvotes: 2

Related Questions