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

I want make JS toggle button.. How Can I Fix It?

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

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

>Solution :

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.

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