Home > Mobile >  Change Src attributes by JavaScript
Change Src attributes by JavaScript

Time:09-02

There is an example on the w3shool site how to change picture (src attribute) by clicking 2 button. One of them is Light On, other is Light Off.

But, I want change picture by 1 button. (On and Off button). I wrote some code, but doesn't work. Can anyone show me, where is my mistake? My code:

<body>

  <img id="myImage" src="/img/pic_bulboff.gif" width="100" height="180">
  
  <p>
  <button type="button" onclick="light()">Light On/Off</button>
  
  </p>
  
  <script>
  function light() {
  if (document.getElementById("myImage").src =="/img/pic_bulbon.gif") {
  document.getElementById("myImage").src == "/img/pic_bulboff.gif"
  } else {
   document.getElementById("myImage").src == "/img/pic_bulbon.gif"
    }
   } 
  </script>
  
  </body> 

Pictures:enter image description here enter image description here


CodePudding user response:

    <img id="myImage" src="img/pic_bulboff.gif" width="100" height="180" />
    <script>
        const img = document.getElementById("myImage");
        // Paths
        const relPath = "img/pic_bulboff.gif";
        const absPath = img.src.slice(0, -relPath.length);
        console.log(img.src);
        console.log(absPath);

        function light() {
          //if (img.src == absPath   "img/pic_bulbon.gif") {
            if (img.src.includes("img/pic_bulbon.gif")) {
                img.src = "img/pic_bulboff.gif";
            } else {
                img.src = "img/pic_bulbon.gif";
            }
        }
    </script>

It doesn't work because .src returns the absolute path so comparing it with relative one won't work. You can extract it like in the example above or you can just use .includes() to check for a substring. Notice that I removed the first / from src, you might need to add it back.

CodePudding user response:

As @Tushar mentioned mind to use single =, also you are likely missing the "." at the image src. It is usually like this

"./img/pic_bulbon.gif"

Then you can change the image src by:

document.getElementById("imageId").src="./img/pic_bulbon.gif";
  • Related