Handling Javascript events not handled by other elements

I am writing a script where I would like to handle mouse events only if they were not previously handled by any other element.

I can connect an event listener to the document object, but it will receive all events regardless of whether they have already been processed.

I have no control over the elements on the HTML page, so I cannot manually stop Propagation () when the event is being processed.

Any ideas?

+5
source share
2 answers

From this article here .

It seems that this is not yet possible.

What event handlers are registered?

W3Cs , , - . :

alert(element.onclick)

, it, undefined, . DOM 3 W3C

eventListenerList

, . , . .

removeEventListener() 

, , , , , removeEventListener().

+1

, - , , . ,

  • JavaScript
  • , ,

, , addEventListener , , . " " - , - , , - . ( jsFiddle)

HTML:

<div id='asdf'>asdf</div>โ€‹

JavaScript:

var target = document.getElementById('asdf');
var original = target.addEventListener;

var updated = function(){
    // Grab the original callback, so we can use it in our wrapper
    var originalFunc = arguments[1];

    // Create new function for the callback, that lets us set a state letting us know it has been handled by someone
    // Finish the callback by executing the original callback
    var newFunc = function(e){
        console.log('haha,  intercepted you');
        e.intercepted = true;
        originalFunc.call(this, e);
    };

    // Set the new function in place in the original arguments 'array'
    arguments[1] = newFunc;

    // Perform the standard addEventListener logic with our new wrapper function
    original.apply(this, arguments);
};

// Set the addEventListener on our target to our modified version
target.addEventListener = updated;

// Standard event handling
target.addEventListener('click', function(e){ 
    console.log('original click'); 
    console.log('intercepted?', e.intercepted);
})
+1

All Articles