Skip to content
Advertisement

Image src won’t change using JavaScript

I feel like I have this right, but for some reason, the addEventListener isn’t functioning how I want it to. When I try to change the img.src below, it still only shows the ‘images/expand.jpeg’ img. I have confirmed that the path to the image is correct, as it does show the ‘images/collapse.png’ when I change the button’s original src to ‘images/collapse.png’.

document.querySelectorAll('.title').forEach(function(){
    let button = document.createElement('img');
    button.classList.add('smallbutton');
    button.src = "images/expand.jpeg"; 
    eachTitleDiv.append(button);
    button.addEventListener('click', function(){
        if (button.src === "images/expand.jpeg") {
            button.src = "images/collapse.png";
        } else if (button.src === "images/collapse.png") {
            button.src = "images/expand.jpeg";
        };
    });
});

Advertisement

Answer

Relative src attribute computes to absolute URL in the DOM

  1. When you access the src attribute, it’s the computed DOM value, and your relative link was computing to the absolute link. (https://yourwebsite.com/images/expand.jpeg === "images/expand.jpeg") returns false
  2. ALWAYS have an alt on your images, like in this case where they don’t load, for visually impaired, SEO so many reasons!

Here is a working snippet where the alt is used to check state rather than the src:

document.querySelectorAll('.title').forEach(function(eachTitleDiv){
    let button = document.createElement('img');
    button.classList.add('smallbutton');
    button.src = "images/expand.jpeg";
    button.alt = "expand"
    eachTitleDiv.append(button);
    button.addEventListener('click', (e) => {
        if (button.alt === "expand") {
            button.src = "images/collapse.png";
            button.alt = "collapse"
        } else if (button.alt === "collapse") {
            button.src = "images/expand.jpeg";
            button.alt = "expand"
        };
    });
});
<h1 class="title">Title 1</h1>
<h2 class="title">Title 2</h2>
<p>Not a title</p>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement