How do I add a callback for setAttribute?
You could, but I would not recommend it.
(function() {
var elementSetAttribute = Element.prototype.setAttribute;
Element.prototype.setAttribute = function() {
whateverFunctionYouWant.call(this);
return elementSetAttribute.apply(this, arguments);
}
})();
jsFiddle .
This will trigger whateverFunctionYouWant()
when you do something like document.links[0].setAttribute('href', '/')
.
You seem to want this to trigger a callback when you change the attribute of the src
elements img
and load a new resource ...
(function() {
var HTMLImageElementSetAttribute = HTMLImageElement.prototype.setAttribute;
HTMLImageElement.prototype.setAttribute = function(attribute, value) {
var image;
if (attribute == 'src') {
image = new Image;
image.addEventListener('load', loaded, false);
image.src = value;
}
return HTMLImageElementSetAttribute.apply(this, arguments);
}
})();
jsFiddle .
Here you can overload with a setAttribute()
third parameter which will be the callback.
In my opinion and experience, I would instead create another function to do this. Modifying prototypes is one thing, but overloading built-in DOM methods to create unnecessary things sounds like a frustrating problem, especially when a developer unfamiliar with what you've done looks at the code.
It goes without saying that if you want the last example to work <IE9, use a fallback attachEvent()
to add an event listener.
source to share
It may not be a golden solution, but
img.setAttribute("src", "http://blabla.com/c.jpg");
img.onload = imageCallback;
function imageCallback() { ... }
If you are interested in jQuery, there is a plugin called waitforimages that might help.
source to share