Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading