Home > Mobile >  Image src won't change using JavaScript
Image src won't change using JavaScript

Time:04-02

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";
        };
    });
});

CodePudding user response:

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 >Title 1</h1>
<h2 >Title 2</h2>
<p>Not a title</p>

  • Related