skip to Main Content

HTML

<div class="icon-menu">
      <img src="../images/menu.png" id="navMenu" onclick="changeToCross()">
</div>

JS

function changeToCross() {
    let menu = document.getElementById('navMenu');
    let src = '../images/menu.png'; 

    if (menu.src === src) {
        menu.src = '../images/close.svg';
    } else {
        menu.src = src;
    }
}

I want to change image source when it will be clicked but this code isn’t working. How can I fix it

2

Answers


  1. The problem you are facing is that element.src is returning fully resolved URL, not the string that you’re setting. For example, if you’re on https://example.com/demo/page and use src="../images/menu.png" then menu.src would return https://example.com/demo/images/menu.png instead of the relative path.

    In order to read the attribute value, you need to use element.getAttribute('src') which returns the raw value of the attribute.

    So your code should be

    if (menu.getAttribute('src') === src) {
    

    To read up more on the topic, you can check what is the difference between properties and attributes in DOM.

    Login or Signup to reply.
  2. An alternative approach, keeping the image sources away from the Javascript, might be to use dataset attributes to store the alternative image source and toggle between that and the source.

    document.querySelector('div.icon-menu img').addEventListener('click',e=>{
      let img=e.target;
          img.dataset.tmp=img.src;
          img.src=img.dataset.alt;
          img.dataset.alt=img.dataset.tmp;
          img.removeAttribute('data-tmp');
    })
    .icon-menu img{
      width:100px;
      height:100px;
    }
    img[src$='svg']{
      border:2px solid red;
    }
    <div class="icon-menu">
      <img src="../images/menu.png" data-alt='https://www.svgrepo.com/show/178323/cross-close.svg' id="navMenu">
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search