8

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
awidgery
  • 1,896
  • 1
  • 22
  • 36
  • 1
    possible duplicate of [firing event on DOM attribute change](http://stackoverflow.com/questions/4561845/firing-event-on-dom-attribute-change) – Sam Abushanab May 14 '15 at 12:27

1 Answers1

3

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

Community
  • 1
  • 1
robC
  • 2,592
  • 1
  • 23
  • 28
  • @awidgery yes I tested it in Chrome 42. When a new image loads the onload event fired. – robC May 14 '15 at 13:34
  • @awidgery are you sure the src is changing? You haven't specified sizes i.e. `sizes="50vw"` – robC May 14 '15 at 13:38
  • 3
    What if you want to measure when the `currentSrc` changes but before the image has loaded? This might be useful if you want to show a loading indicator, for example. You would need a way to know when the image request starts and stops—and `currentSrc` can change at any time, e.g. on resize, or if `sizes` is changed. – Oliver Joseph Ash Mar 03 '18 at 17:18