dgzz
dgzz

Reputation: 2999

Simple javascript change image not working

I want to change an image's src on click of a link. I got a javascript snippet and tried to integrate it but it doesn't work.Im

Here's my HTML:

<html>
<head>
<meta charset="utf-8">

<link href="styles/main.css" rel="stylesheet" type="text/css">
</head>
<body>
<script src="styles/script.js"></script>
  <img id="bgimage" src="images/1.jpg"/>

  <nav id="nav"><a href="" onclick="changeImage()">A</a> | B |
  </nav>

</body>
</html>

Here is my script.js:

var imageId = document.getElementById("bgimage");
    function changeImage() {

        if (imageId.src == "images/1.jpg") 
        {
            imageId.setAttribute("src","images/2.jpg");
        }
        else 
        {
            imageId.setAttribute("Src","images/1.jpg");
        }
    }

Upvotes: 0

Views: 84

Answers (2)

Oriol
Oriol

Reputation: 288100

You must place your script just before </body>, or run it at onload.

If not, you run

var imageId = document.getElementById("bgimage");

before loading the image to the DOM, so imageId is null.


Anyway, you could improve your function to

var images = ["images/1.jpg", "images/2.jpg" /*, ... */];
function changeImage() {
    imageId.src = images[(images.indexOf(imageId.src)+1) % images.length];
}

Upvotes: 1

markasoftware
markasoftware

Reputation: 12662

This issue is occurring because the script appears in the html before the <img> element. Therefore, the code tries to find the img element, but it can't because the js code executes before the rest of the html is parsed. Correct it by putting the js include tag just before </body>:

<html>
<head>
<meta charset="utf-8">

<link href="styles/main.css" rel="stylesheet" type="text/css">
</head>
<body>
  <img id="bgimage" src="images/1.jpg"/>

  <nav id="nav"><a href="" onclick="changeImage()">A</a> | B |
  </nav>

<script src="styles/script.js"></script>

</body>
</html>

Or, you might want to use DOMContentLoaded to wait until the html has been parsed. Change the js to this, in that case:

var changeImage;
document.addEventListener('DOMContentLoaded',function(){
var imageId = document.getElementById("bgimage");
changeImage=function() {

    if (imageId.src == "images/1.jpg") 
    {
        imageId.setAttribute("src","images/2.jpg");
    }
    else 
    {
        imageId.setAttribute("Src","images/1.jpg");
    }
}
},false);

Or you could call document.getElementById() every time changeImage is called

Upvotes: 1

Related Questions