Reputation: 944
I have one very simple Javascript code. The code is to change the source of the image when the page loads. It goes something like this:
window.onload = initAll;
function initAll(){
document.getElementById("imgSlider").src = "menuBack.jpg";
}
Now, this works perfectly fine. Look at the code below.
window.onload = initAll;
function initAll(){
var imgSrc = document.getElementById("imgSlider").src
imgSrc = "menuBack.jpg";
}
Shouldn't this code perform as the code above? I guess, it should. Is there something wrong in the lower code? I use Mozilla Firefox(latest version). Could this be the problem of the browser?
Upvotes: 2
Views: 81
Reputation:
window.onload = initAll;
function initAll(){
var img = document.getElementById("imgSlider");
img.src = "menuBack.jpg";
}
Upvotes: 2
Reputation: 16184
The second piece of code should definitely do something else.
The first part:
document.getElementById("imgSlider").src = "menuBack.jpg";
means that you store the string "menuBack.jpg"
into document.getElementById("imgSlider").src
.
However, the second part:
var imgSrc = document.getElementById("imgSlider").src
imgSrc = "menuBack.jpg";
means that you first store document.getElementById("imgSlider").src
into imgSrc
, but then overwrite that by storing "menuBack.jpg"
into imgSrc
.
That is something different.
Upvotes: 3
Reputation: 27855
do like
var imgSrc = document.getElementById("imgSlider");
imgSrc.src = "menuBack.jpg";
You should have the dom element in your variable to apply the value to its attribute. Other ways you just have a string which is not dom element.
Upvotes: 3