Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 251
Omar Abid Avatar asked Oct 09 '10 22:10

Omar Abid


People also ask

How do you check if there is an event listener in JavaScript?

Right-click on the search icon button and choose “inspect” to open the Chrome developer tools. Once the dev tools are open, switch to the “Event Listeners” tab and you will see all the event listeners bound to the element. You can expand any event listener by clicking the right-pointing arrowhead.

Are the event handlers in JavaScript?

JavaScript Event HandlersEvent handlers can be used to handle and verify user input, user actions, and browser actions: Things that should be done every time a page loads. Things that should be done when the page is closed. Action that should be performed when a user clicks a button.

Is an event handler HTML or JavaScript?

Event handlers are the JavaScript code that invokes a specific piece of code when a particular action happens on an HTML element. The event handler can either invoke the direct JavaScript code or a function.

How are event handlers registered in JavaScript?

You can register event handlers for either phase, bubbling or capturing, by using the function addEventListener(type, listener, useCapture) . If useCapture is set to false , the event handler is in the bubbling phase. Otherwise it's in the capture phase. The order of the phases of the event depends on the browser.


1 Answers

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

like image 199
BrunoLM Avatar answered Sep 23 '22 17:09

BrunoLM