2

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?

3
  • aren't youi missimng a semicolon after .src ? Commented May 11, 2013 at 9:40
  • 3
    @rene: Javascript has "automatic semicolon insertion" Commented May 11, 2013 at 9:42
  • 1
    @MM. that is true, which doesn't mean you should rely on it, but I admit that is not the root cause for the problem... Commented May 11, 2013 at 9:47

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2
window.onload = initAll;
function initAll(){
     var img = document.getElementById("imgSlider");
     img.src = "menuBack.jpg";
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.