skip to Main Content

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


  1. You could use image.onload and image.onerror to understand what’s happening.

    var image = document.getElementById('myImage');
    
    image.addEventListener('click', function(){
        changeImage();
    });
    image.onerror = function(e) { console.log('Loading failed', e); }
    image.onload= function(e) { console.log('Loading successful', e); }
    
    function changeImage(){
        image.src = 'img/lab.svg';
    }
    
    Login or Signup to reply.
  2. 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 its src property.

    Instead, you should assign to the image’s src attribute:

    const button = document.getElementById('image-button');
    const image = document.getElementById('image');
    
    button.addEventListener('click', function(){
      changeImage();
    });
    
    function changeImage(){
      image.src = 'img/lab.svg';
    }
    <img id="image" src="img/vault.svg" alt="">
    <button id="image-button"> </button>

    Note: I changed the variable names and element IDs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search