Kevin Sylvestre
Kevin Sylvestre

Reputation: 38012

jQuery Test if DOM Element Supports "load" Event

Is it possible to check if a jQuery object supports firing an event handler for a specific event? I have a function that takes a DOM element and I want to listen for "load" to fade in the element using the following:

element.css({ opacity: 0.0 });
element.bind('load', function() { $(this).animate({ opacity: 1.0 }); });

Unfortunately, this fails if the passed in element is not an image (as it will always be transparent). Thanks!

Upvotes: 1

Views: 425

Answers (2)

Adam Terlson
Adam Terlson

Reputation: 12730

Since my comment seemed to be an acceptable route, here's a more complete answer:

Since it would seem that your function will only work if the passed element is an image, simply test to see if the element passed in is an image:

function conditional(element) {
    if(element.tagName == "IMG") {
        element.css({ opacity: 0.0 }).bind('load', function() { $(this).animate({opacity: 1.0 }); });
    }
}

http://jsfiddle.net/cHsMx/2/

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 185893

jQuery can bind the 'load' event to any DOM element (<== This never fails). However, that event does not fire at any DOM element (It fires at window, document, scripts, stylesheets, images, iframes, etc.).

If the 'load' event does not fire at a given element (for instance, a DIV), then there is no point in binding a load handler to that element.

Upvotes: 1

Related Questions