Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if event listener is supported

Is it possible to detect if certain events are supported in certain browsers? I can detect if the browser supports document.addEventListener, but I need to know if it supports the event DOMAttrModified. Firefox and Opera support it, but Chrome and others do not.

like image 914
Ben Avatar asked Dec 30 '10 11:12

Ben


People also ask

How do I know if my event listeners are attached?

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.

Why is event listener not working?

If your event listener not working is dependent on some logic, whether it's about which element it'll listen on or if it's registered at all, the first step is to check that the listener is indeed added to the element. Using a breakpoint in the developer tools , a logpoint or console.

How do I check if an element has a click event?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked. Here is the HTML for the examples in this article.


1 Answers

Updated answer:

Yes, you can feature-detect this. Create an element, listen for the event, and change an attribute on the element. In my tests, you don't even have to add the element to the DOM tree, making this a nice, contained feature detection.

Example:

function isDOMAttrModifiedSupported() {
    var p, flag;

    flag = false;
    p = document.createElement('p');
    if (p.addEventListener) {
        p.addEventListener('DOMAttrModified', callback, false);
    }
    else if (p.attachEvent) {
        p.attachEvent('onDOMAttrModified', callback);
    }
    else {
        // Assume not
        return false;
    }
    p.setAttribute('id', 'target');
    return flag;

    function callback() {
        flag = true;
    }
}

Live copy

Firefox triggers the callback on all of the modifications above; Chrome on none of them.


Original answer:

You can feature-detect whether some events are supported, as shown on this handy page. I don't know if you can test specifically for that one, but if you can, that code may well get you started.

Update: I dumped Kangax's code into JSBin and tried it, doesn't look like that sniffing technique works for that event (unless I have the name spelled incorrectly or something; Firefox is showing "false"). But my technique above does.

like image 177
T.J. Crowder Avatar answered Sep 29 '22 18:09

T.J. Crowder