Omar Abid
Omar Abid

Reputation: 15976

How to check if an event handler exist using jQuery or JS?

I want to check if an event is available or not before binding a function to it. The problem is that Google Chrome support the event "loadedmetadata" in the Video element while FireFox don't.

I did the following

$('video').bind('loadedmetadata', videoloaded);
videoloaded();

It worked well in Firefox but when I tried in Chrome, the function was executed twice (which is logical). I want to check if loadedmetadata event handler exists or not to run the function only one time in each browser.

If such possibility doesn't exist, any intelligent work around for this?

Upvotes: 5

Views: 12998

Answers (1)

BrunoLM
BrunoLM

Reputation: 100322

Check the $video.data("events") if this object contains your event, since you are using .bind all events of this element will be stored in this object.

var $video = $("#video");
var $ve = $video.data("events");

// checking if a `loadedmetadata` object exists in `data("events")`
if ($ve != null && typeof($ve.loadedmetadata) !== undefined)
{
    // has loadedmetadata event
}

Full working example on jsFiddle

Upvotes: 5

Related Questions