Search code examples
javascriptwindowblurevent-bubbling

Prevent event triggering on bubbling and on capturing in JavaScript


Is it possible to prevent event triggering on bubbling and on capturing in JavaScript?

The e.stopPropagation() is not what I am looking for.

In my case I would like only a direct window blur to trigger the event. Triggering the blur event on window on every child control blur affects performance. (I believe that it is not related to the question, but still in order to avoid the xyz problem I will mention that I am using the blur event on window to check that the blur happened due to iframe click and in case it did, then I run some code. I.e. what I need here is a way to attach a blur listener to window, so that the blur listener would run only on window blur, but not on its children blur.)

Maybe there is a way to add an event listener to a target phase of window blur only? Or will the listener be always called on bubble and on capture and it is impossible to avoid?


Solution

  • event bubbling travels from child to parent. So it is essentially event capturing which you want to prevent.

    When you add a event listener using

    window.addEventListener("focus", callback, true/false)
    

    This third argument suggest capturing or bubbling. So if you will just keeps it false event will just bubble and since window is the top most element it wont be propagated to anywhere else.