I'am trying to detect if the source of a image is changed.
In my case the src is changed from jquery, and i have no right's to change the jquery file.
So im trying to detect the src change from a img element.
I would like to see the source if the 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 alert react's and shows me the src, but not on a src change from jquery
DOMAttrModified
might work, no idea about that...but onload works definitely fine for me. Here's the fiddle with the demo. http://jsfiddle.net/QVqhz/
You could do it, however it would only be supported by new browsers that implement the DOM mutation events...
divimg.addEventListener("DOMAttrModified", function(event) {
if (event.attrName == "src") {
// The `src` attribute changed!
}
});
Every time the src
attribute is changed the browser will immediately go off and fetch the image. Once the image is returned to the browser the browser will trigger the loaded
event on the image element. So you can effectively monitor src
changing by setting a callback on this event. You could 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");
Analysis
load
event is triggered when src
attribute of <img />
is changed or set
If user didn't write src
attribute in <img />
, browser will fill out src
attribute automatically (such as data:image/png;base64,...) to prevent 204 Error. This will also trigger load
event.
Conclusion
Basically use load
event, but check whether it is default image or not. (Probably, default image would be 1 x 1 pixel)
- Assumption - your image is bigger than 1 x 1 pixel
Solution
$('img').load(function() {
var imageObj = $(this);
if (!(imageObj.width() == 1 && imageObj.height() == 1)) {
console.log('Image source changed');
}
});
var img = document.querySelector("#img_div img"),
observer = new MutationObserver((changes) => {
changes.forEach(change => {
if(change.attributeName.includes('src')){
console.dir(img.src);
}
});
});
observer.observe(img, {attributes : true});
I think there is no event for that, 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
}