Reputation: 325
I have trouble understanding the problem that's preventing me from run some JavaScript code. On clicking the button it should change the image, which is saved in an array. The images are in the same folder as the html document, so there is no error in the path.
While it works on Firefox, it doesn't work on Chrome and Edge.
My Chrome console says Can not set property of 'src' of null.
My Edge console says Unable to set property 'src' of undefined or null reference.
This is the line that is causing the problem:
imgElem.src = imgArr[a];
This is the whole code:
"use strict"
var a = 0;
var imgArr = ["sl0.jpg", "sl1.jpg", "sl2.jpg"];
var imgElem = document.getElementById("img");
function changeImg() {
imgElem.src = imgArr[a];
if (a < imgArr.length - 1) {
a++;
} else {
a = 0;
}
}
<img id="img" src="sl0.jpg" width="200px" />
<br /><button type="button" onclick="changeImg()">Click me</button>
I would appreciate it if you could explain the problem. The source obviously isn't null, since it's referencing an "object" in the array.
Edit: As suggested by AlbertoSingaglia, I tried to find the imgElem in console. It found it in Firefox, while it didn't find it in Chrome.
Upvotes: 1
Views: 1494
Reputation: 614
Where does your script resides in the html markup? is it in the head?
That might be the problem because in that case it will run before the html has rendered.
Try one of these things:
1) move script tag to just before the body ends.
<body>
<!-- markup -->
<script></script>
</body>
or
2) move line var imgElem = document.getElementById("img");
inside the function changeImg()
like:
"use strict"
var a = 0;
var imgArr = ["sl0.jpg", "sl1.jpg", "sl2.jpg"];
function changeImg() {
var imgElem = document.getElementById("img");
imgElem.src = imgArr[a];
if (a < imgArr.length - 1) {
a++;
} else {
a = 0;
}
}
Upvotes: 3