0

I'm making a little point-and-click HTML game, while learning myself to code.

When I was testing stuff, I ran into a problem. My javascript changes an image, which I did not expect it to do.

Somewhere in my code is this image.

<img src="icon.jpg" id="img2">

And somewhere else is this script.

 <script >
 if (document.getElementById('img2').src="images.jpg") {
 window.alert("hi");
 }
 else { window.alert("bye");}
    </script>    

So, if the image source of img2 is images.jpg, you'll get an alert saying "hi", and if it's not images.jpg, you;ll get an alert saying "bye". Obviously, the source of that image is icon.jpg, which is not images.jpg, so I expected it to say "bye". But it doesn't do that. When refreshing or loading the page, the source of img2 is immediately changed to images.jpg and I get a "hi" alert. How can I prevent that from happening?

1
  • document.getElementById('img2').src == "images.jpg") -> you need to compare with double equal sign : )) Commented Jan 3, 2016 at 10:54

2 Answers 2

2

make the equals a double equals. if (document.getElementById('img2').src=="images.jpg") {

function changeImg(){
  document.getElementById('img2').src="http://placebear.com/200/300";
  window.setTimeout(checkImg,1000);

}
  
  function checkImg(){
  if (document.getElementById('img2').src=="http://placebear.com/300/200") {
 window.alert("hi");
 }
 else { window.alert("bye");}
  }
checkImg();
<img src="http://placebear.com/300/200" id="img2"/>
<button type="button" onclick="changeImg()">Click to change and run test</button>

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

5 Comments

Thanks! :) Completely forgot about that. Also, that was a VERY quick response!
you're welcome. Don't think there's a single person on here that hasn't done exactly the same thing at some stage. Happy new year.
Another question because of this one. I've now this code <img src="images.jpg" id="img2"> and this code <area href="javascript:replaceImage('img2', 'icon.jpg', 'l2')" shape="rect" coords="100,350,150,400">. Which means, originally there's an image with source images.jpg (alerting "hi"), which is changed by clicking to icon.jpg. After that change it won't alert me "bye". How can I make it alert "bye"?
can't see a change in the context of the question, should work, I'll do a code snippet to show it working. back in a mo.
Thank you very much. As I'm a new user I cannot upvote yet, but I would upvote your answer if I could :)
1

Change your script as below:

if ( document.getElementById('img2').getAttribute('src') == "images.jpg" ) {
 	window.alert("hi");
  
}
else { 
	window.alert("bye");
}
<img src="icon.jpg" id="img2">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.