How to pass an image URL to a function via onclick without repeating the same URL twice

I’m trying to pass the “image1.jpeg” source URL to the “toggleImage” function via onclick without having to input the same URL again. Is there a way to reference the “image1.jpeg” URL in the onclick? I experimented with the “this” keyword but couldn’t get it to work.

As is, it works fine but I don’t like redundancy of using the same URL twice. Any suggestions?

<img src="/image1.jpeg" alt="Alt Name" id="Test" onclick="toggleImage('/image1.jpeg','/image2.jpeg','Test' )">
function toggleImage(src1, src2,imgID) {

    if (document.getElementById(imgID).src == src2)
    {
        document.getElementById(imgID).src = src1;
    }
    else 
    {
        document.getElementById(imgID).src = src2;
    }
}

Answer

You could set up something like the below:

<img src="image1.jpg" onclick="switchImage(event)" data-second="image2.jpeg">
function switchImage(e) {
    e = e || window.event;
    let target = e.target || e.srcElement;
    
    let originalSrc = target.src;
    let secondImage = target.dataset.second;
    
    target.src = secondImage;
    target.dataset.second = originalSrc;
}

Leave a Reply

Your email address will not be published. Required fields are marked *