0

We want to add functionality to an already existing page using a browser extension. Suppose an element already has functions bound to its onclick event. I am binding a new function to the onclick of that element. I want to have my function run before all the other functions that have been bound to that event before. I don't want them to begin executing until my function is finished running.

I want to know how I can I bind my new function this way in JavaScript.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jimmy Page
  • 343
  • 1
  • 6
  • 12
  • are the events binded with addEventListener or by callback direct affectation? onclick=.. – Sebas Jun 26 '12 at 23:54
  • A simple way to accomplish this would be to have yours run on mouse down since click is onmouseup. – Travis J Jun 26 '12 at 23:55
  • They are binded with addEventListener. – Jimmy Page Jun 27 '12 at 00:00
  • The problem with mouse down is I want the other functions to start after my function finishes which may take some time. – Jimmy Page Jun 27 '12 at 00:01
  • @jimmy I haven't tested this at all, but I think it may work. Try: `element.onclick = function() { doYourAction(); element.onclick(); }` Please let me know if this works :-) Also, if your action involves ajax/anything asynchronous you need to put the `element.onclick()` in it's callback instead so that it finishes first. – nbrooks Jun 27 '12 at 00:15
  • Please note that functions are bound [as event listeners] to elements, not the other way round. – Bergi Jun 27 '12 at 00:24

1 Answers1

0

You can't really. Event listeners are usually executed in the order they were attached to elements, and you can't get those already added. If your plugin will not execute before any other listener-adding code, your only chance is to get into the event dispatch process as early as you can.

The best way I can think of is to add a listener for the capture phase at the highest point of the dom:

document.documentElement.addEventListener("click", function(e) {
    if (e.target == theElementInQuestion) // or check for e.target.id...
        // do something with the event like
        e.stopImmediatePropagation();
}, true /* sic! */);
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375