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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With