0

Hey i want to change a image when the img is clicked with javascript it works once if i click the picture it changes the scr but doesnt change it back

function ImgClick() {
  var img = document.getElementById("b1")
  if (img.src = "img/RoteAmpel.jpg") {
    img.src = "img/GrueneAmpel.jpg";
  } else {
    img.src = "img/RoteAmpel.jpg";
  }


}
<!DOCTYPE html>
<html>

<head>
  <title>Mouse Events</title>
  <meta charset="UTF-8">

</head>

<body>
  <h3>Mouse Events</h3>
  <img src="img/RoteAmpel.jpg" alt="Bildwechsel" title="Bildwechsel" id="b1" onclick="ImgClick()" />


</body>

</html>

4
  • if(img.src="img/RoteAmpel.jpg") <---- assignment, not comparison. Commented Nov 29, 2021 at 16:31
  • 2
    so i gotta do == ? when i write if(img.src=="img/RoteAmpel.jpg") it doesnt even change it once Commented Nov 29, 2021 at 16:32
  • And most developers tend to use === instead, to avoid unexpected behavior when comparing values of different types Commented Nov 29, 2021 at 16:34
  • console.log(img.src, img.src == "img/RoteAmpel.jpg") is it what you expect? Commented Nov 29, 2021 at 16:34

1 Answer 1

2

There are two problems with your code:

1. Assignment vs Comparison

You're assigning the src instead of making a comparison:

if (img.src="img/RoteAmpel.jpg") { }

should be

if (img.src === "img/RoteAmpel.jpg") { }

2. img.src might not be what you expect

When accessing img.src you'll get the full qualified URL including protocol, domain etc.

To compare the actually attribute's value use this:

img.getAttribute('src')

You can test it yourself:

function test() {
  var img = document.getElementById("b1")
      
  console.log(img.src);
  console.log(img.getAttribute('src'));
 }
    
test();
<img id="b1" src="img/RoteAmpel.jpg">

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

1 Comment

Yes thanks for the help you didnt only help me to fix it i also understood what was wrong because of the function test you gave me thank you :)

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.