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

Suppose I have a tag <img>

:

<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 one srcset

it is using:

document.getElementById("my_tag").currentSrc

      

How to detect when the currentSrc

event changes and fires?

To prevent the shouts of "duplicate!" I can confirm that it is not triggered in Chrome using the DOM MutationObserver here here using jQuery observe or using an event onload

:

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

      

I think this has to do with the fact that when used srcset

, it doesn't update the DOM when currentSrc changes.

+3


source to share


1 answer


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

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

      



Related entry in Event Handling with Browser Load

+1


source







All Articles