1

I want to attach click event handlers to all the elements in a page that I don't control (e.g.- stackoverflow homepage). Capturing clicks by assigning click handlers to every element is a tedious task. So I decided to do this instead:

window.addEventListener("click", function (e) {
      //code
});

Is it guaranteed that my event handler will finish execution before something happens that makes the element inaccessible, for example element's own click handler deleting its parent from DOM?

2 Answers2

0

Yes, the event will be completed unless you try to tag a deleted element after it's trigged or another kind of error occurs. It's a basic example of DOM event delegation.

Tiago Alves
  • 2,082
  • 10
  • 30
0

Yes. Event handlers run synchronously in the page. However, if you delete an element, that element is immediately removed from the DOM tree. You won't see any changes in the browser until the event handler code finishes, but the node won't be there. However, removing an element from the page won't stop the event handler from executing.

Try this:

document.querySelector('#id1').addEventListener('click', function() {
  console.log (this.parentNode); // the DIV node
  this.parentNode.parentNode.removeChild(this.parentNode); // remove the DIV
  console.log(document.querySelector('#id1')); // null. Node no longer in the DOM.
  console.log(this.parentNode); // though detached from the DOM, the object still exists
                                // and has a parent.
  var acc = 1;                        
  for (var i = 0; i < 1000000; i++) {
    acc += 2 * i;
  }
 
  alert(acc);
  
  // though not in the DOM, the h2 is still visible in the page, and the browser is frozen, until the loop finishes and the alerts disappers.
});
<div>
 <h1 id="id1">Click here</h1>
</div>

As you see, when you click on the h2 element, it is removed from the DOM (as shown in the console). However, it still visible until the alert window disappears. JavaScript code execution, if not done in a web worker, blocks the rendering.

Oscar Paz
  • 16,845
  • 3
  • 21
  • 36
  • what happens when there's a loop that runs billions of times in event handler of an anchor element which when clicked, loads a new page? Is the behavior consistent across all browsers? –  Mar 15 '18 at 16:54