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
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 onhttps://example.com/demo/page
and usesrc="../images/menu.png"
thenmenu.src
would returnhttps://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
To read up more on the topic, you can check what is the difference between properties and attributes in DOM.
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.