Search code examples
javascriptimageonclicksrc

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

  • 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">