Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing Image onclick with JavaScript

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading