April 5, 2012

How to add a callback for setAttribute?

Question by Steffi

Is it possible to add a callback on setAttribute on Prototype ?

For this example, I would like to show an alert("done !") when setAttribute() is finished.

img.setAttribute("src", "http://blabla.com/c.jpg");

Answer by alex

You could, but I wouldn’t recommend it.

(function() {

    var elementSetAttribute = Element.prototype.setAttribute;

    Element.prototype.setAttribute = function() {
        whateverFunctionYouWant.call(this);

        return elementSetAttribute.apply(this, arguments);
    }

})();

jsFiddle.

This will call whateverFunctionYouWant() when you do something such as document.links[0].setAttribute('href', '/').

You seem to want this to call a callback when you change the src attribute of img elements and the new resource has loaded…

(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.

You could overload setAttribute() here with a third parameter, which would be the callback.

In my opinion and experience, I’d create a different function instead for doing this. Modifying prototypes is one thing, but overloading native DOM methods to do extra things sounds like inviting trouble, especially once a developer unfamiliar with what you’ve done looks at the code.

It goes without saying that if you want the latter example to work < IE9, use the attachEvent() fallback for adding the event listener.

Answer by Starx

May be not the golden solution but

img.setAttribute("src", "http://blabla.com/c.jpg");
img.onload = imageCallback;

function imageCallback() { ... }

If you are interested in jQuery, there is plugin called waitforimages that might help.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!