I was learning about a few DOM events, and I tried to use the ‘blur’ event on the HTML body.
First with onblur
document.body.onblur = () => {
dosomething();
}
and with AddEventListener
document.body.addEventListener("blur", ()=>{
dosomething();
})
However, only using onblur works, so why didn’t it work with addEventListener("blur") in this case?
Is there any difference between them?
2
Answers
In the case you described, the reason why using onblur works while addEventListener("blur") doesn’t work is because the blur event doesn’t bubble up the DOM tree.
When you use onblur directly on an element like document.body.onblur, you’re essentially setting a property directly on that element to listen for the blur event. This works because blur is a non-bubbling event, meaning it only applies to the element itself. So, when the blur event happens on the body, it triggers the event handler directly attached to it.
However, when you use addEventListener("blur"), you’re setting up an event listener that listens for the blur event to bubble up the DOM tree. Since blur doesn’t bubble, attaching an event listener for it won’t work as expected on elements other than the one directly affected by the blur event.
So, in summary:
onblur works because it directly attaches an event handler to the element itself.
addEventListener("blur") doesn’t work because blur doesn’t bubble up the DOM tree, and addEventListener listens for events that bubble.
If you need to capture blur events on the body, using onblur directly on document.body is the appropriate approach.
Interestingly it seems to have different behaviour depending on the type of element it is put on.
I think the problem here is what is described in this answer:
Here’s an example of what happens on different elements: