0

Very simple thing which I am not able to do. I have two images viz. try.jpg and menuBack.jpg. Initially, I put try.jpg as image source but as soon as the page loads I want to change it to the other image.

HTML:

<img id="imgSlider" width="284px" height="284px" src="try.jpg"/> 

JavaScript:

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

What's wrong here?

2 Answers 2

5

Your code is the 'wrong way around'. So you need to assign menuBack.jpg to document.getElementById("imgSlider").src;

Also you were using double == which is a logical operator for "is something equal to something else?".

Finally, add the brackets after initAll().

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

Here is a JSFIDDLE of it working (obviously a fake image location, but if you inspect the element with your browser dev tools then you can see it has changed).

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

3 Comments

Ok that worked. BUt stilll didnt get what was wrong with the code above. I shoudl ahve used = instead of ==. thats fine. But it still didnt. As soon as i copy pasted the jsFiddle code, it worked
Change it to my single line of code. This line is grabbing the element imgSlider and assigning menuBack.jpg to it's src property. Before you were grabbing this property, saving it to another variable and then changing that variable later. This doesn't change the original src property, it just changes the variable.
Also, add the () to initAll().
0

So what you'll want to do is something like this:

document.getElementById("imgSlider").src = "menuBack.jpg"; 

What you are looking to do is actually an assignment statement - for that you use only one =- equals character. You use two == equals characters to do conditional expressions (if..then..else).

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.