Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Javascript event fired when currentSrc for an <img> tag changes?

Suppose I have an <img> tag:

<img id="my_tag" src="/default.jpg" srcset="/small.jpg 500w, /medium.jpg 1000w, /large.jpg 2000w">

When I load the page, JavaScript can tell me which of the srcset it is using:

document.getElementById("my_tag").currentSrc

How can I detect when currentSrc changes and fire an event?

To stave off the cries of "duplicate!" I can confirm that it doesn't fire in Chrome using DOM MutationObserver code here, using jQuery observe, or using the onload event:

var my_tag = document.getElementById("my_tag");
my_tag.onload = function(){
    alert("CHANGED");
    console.log( "Src changed to " + my_tag.currentSrc );
};

I think this is because when srcset is used it doesn't seem to update the DOM when currentSrc changes.

like image 781
awidgery Avatar asked Nov 09 '22 13:11

awidgery


1 Answers

You can use the 'onload' event of the image:

var my_tag = document.getElementById("my_tag");
my_tag.onload = function(){
    console.log( "Src changed to " + my_tag.currentSrc );
}

A related post on Cross-browser image onload event handling

like image 144
robC Avatar answered Nov 14 '22 22:11

robC