Why Does Body.onfocus Trigger But Not Body.addEventListener('focus')?
Solution 1:
TL;DR:
Use window.addEventListener or document.addEventListener, but *never document.body.addEventListener.
The issue
The issue is, the <body> doesn't have the focus or blur events; the document does. Probably for compatibility with very old sites, however, the <body> element allows onfocus and onblur to be triggered when a focus / blur occurs on the document.
Thus, using window.addEventListener should work in most cases since the event bubble sfrom the document to the window. And since all other events also bubble from the body, it's probably best to just use window.addEventListener for other events too (*unless there is a specific reason not to, such as when propagation is stopped).
This issue is also apparently the case for the scroll event, since the <html> tag is probably what actually scrolls. Again, using window.addEventListener would catch it when it bubbled.
Post a Comment for "Why Does Body.onfocus Trigger But Not Body.addEventListener('focus')?"