I am trying to have an invisible button on a small part of the page to change the background image.
But, the button doesn’t change the image to the one specified.
var image = document.getElementById('myImage');
image.addEventListener('click', function(){
changeImage();
});
function changeImage(){
image.src = 'img/lab.svg';
}
<img src="img/vault.svg" alt="">
<button id="myImage"> </button>
2
Answers
You could use
image.onload
andimage.onerror
to understand what’s happening.You seem to confuse your button reference (variable
image
) with the<img>
element.Make sure you use sensible names (for your variables and IDs) to avoid confusions.
You save the button reference in the variable
image
, and try to change itssrc
property.Instead, you should assign to the image’s
src
attribute:Note: I changed the variable names and element IDs.