Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JavaScript or jQuery how to check if event exists on the window?

Setup

I've attached an event to the 'window' object, and I would like to check that it's there via code.

window.addEventListener('beforeunload', function(e){ /*...*/ }, false)

Attempts

I've tried the simple, and jQuery, without luck. I have more attempts up on jsFiddle.

window.beforeunload //is undefined as is window.onbeforeunload

$(window).data('events') //not working either

Is this possible?

There are similar questions (here and here) about the DOM, and other elements, but none of the approaches in those that I have tried have worked.

like image 350
Nick Josevski Avatar asked Feb 14 '12 01:02

Nick Josevski


People also ask

How do I check if an event listener exists?

To check whether dynamically attached event listener exists or not with JavaScript, we can get and set the element's listener attribute. export const attachEvent = ( element: Element, eventName: string, callback: () => void ) => { if (element && eventName && element. getAttribute("listener") !== "true") { element.

How do you check if an element already has an event listener JavaScript?

To check if an element has event listener on it with JavaScript, we can call the getEventListeners function in the Chrome developer console. getEventListeners(document. querySelector("your-element-selector")); in the Chrome developer console to select the element we want to check with querySelector .

What is jQuery live event?

jQuery live() Method The live() method attaches one or more event handlers for selected elements, and specifies a function to run when the events occur. Event handlers attached using the live() method will work for both current and FUTURE elements matching the selector (like a new element created by a script).


1 Answers

You can use the in operator...

'onbeforeunload' in window;  // true (if supported)

If supported, the property will exist, though the value will be null.

like image 155
user1106925 Avatar answered Oct 21 '22 14:10

user1106925