1

Suppose I have http://www.w3schools.com/js/tryit.asp?filename=tryjs_prompt page. Now I have event listener on click action, something like this:

document.addEventListener('click', function() {
    MyMagicHere();
});

Now in case of clicking on button "Try it" MyMagicHere() is interupted by JS popup. I want MyMagicHere() to be performed even in case of clicking on this button. Is there any way/workaround how to handle this situation?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Petr Krčmárik
  • 221
  • 1
  • 2
  • 13

2 Answers2

2

You could use the 'mouseup' event instead of the 'click' event to trigger your MyMagicHere call, as it will fire before the 'click' event does on the button.

Cameron
  • 434
  • 2
  • 4
  • if I try your suggestion in chrome console it does not seem that this is working. `var test = ""; document.addEventListener("mouseup", function(){ test = "worked"; }); var test2 = ""; document.addEventListener("mousedown", function(){ test2 = "worked"; });` after click if I simply do `test` or `test2` it showing in both cases that `test=""` @cameron morrow – Petr Krčmárik Jan 15 '16 at 21:34
  • Are you sure that when you check the value of test or test2 you are in the same scope that you declared it in? – Cameron Jan 15 '16 at 21:49
  • Right on! I'd recommend using @Madox2's answer though, it's a cleaner solution. – Cameron Jan 15 '16 at 22:08
1

Try to set useCapture parameter of addEventListener to true. Then your listener will be executed in capture phase before being executed any event target.

document.addEventListener('click',function(){
   MyMagicHere();
}, true);

This is the concept of capturing and bubbling events. You can see more in this question

Community
  • 1
  • 1
madox2
  • 49,493
  • 17
  • 99
  • 99