Detect img src change

I am trying to determine if the source code of an image has changed.

In my case, src is changed with jquery, and I have no right to modify the jquery file. Therefore, I am trying to detect a src change from an img element.

I would like to see the source if src is changed, just for testing

This is my current code:

var divimg = document.getElementById("img_div"); divimg.onchange = alert(divimg.getElementsByTagName('img')[0].src); 

On the page, load the warning and show me src, but don't change src from jquery

+4
source share
5 answers

DOMAttrModified may work, I don’t know about it ... but onload works definitely fine for me. Here is a violin with a demo. http://jsfiddle.net/QVqhz/

+7
source

You can do this, however it will only be supported by new browsers that implement DOM mutation events ...

 divimg.addEventListener("DOMAttrModified", function(event) { if (event.attrName == "src") { // The `src` attribute changed! } }); 
+5
source

Each time the src attribute is changed, the browser immediately turns off and retrieves the image. When the image is returned to the browser, the browser loaded event on the image element. This way you can effectively track src changes by setting a callback to this event. You can do something similar to the following code example.

 var img = $("<img />"); img.load(function() { console.log("loaded"); }); img.attr("src", "http://static.adzerk.net/Advertisers/ecc536e9e1204b7faccb15621f27d7bc.jpg"); 
+4
source

Analysis

  • load event is fired when the src <img /> attribute is changed or set.

  • If the user did not write the src attribute in <img /> , the browser will automatically fill in the src attribute ( for example, data: image / png; base64, ... ) to prevent error 204. This will also trigger the load event.

Conclusion

  • Mostly use the load event, but check if this is the default image or not. ( Perhaps the default image will be 1 x 1 pixel )

    • Assumption - your image is larger than 1 x 1 pixel

Decision

 $('img').load(function() { var imageObj = $(this); if (!(imageObj.width() == 1 && imageObj.height() == 1)) { console.log('Image source changed'); } }); 
+1
source

I think there is no event for this, you can create your own "event":

 var divimg = document.getElementById("img_div"), prevSrc; setInterval(function() { if (divimg.src != prevSrc) { prevSrc = divimg.src; onSrcChange(); } }, 1000); // 1000ms = 1s function onSrcChange() { // do something } 
0
source

Source: https://habr.com/ru/post/1413196/


All Articles