简体   繁体   中英

JavaScript listen for all focus/blur events

So I'd like some JavaScript which listens for all potential focus/blur events on the page. I can do this for click events quite easily:

document.addEventListener('click', function (e) { console.log('click!') })

Any time any element is clicked, the event will trigger, even if the node was inserted after the event listener was added.

I'd like to do the same for focus events, but they are only triggered on individual elements, and never bubble up to the document.

How can I accomplish this? Is the only way to walk the DOM every few seconds and re-listen in case a new input element has been added?

You can use the focusin and focusout events which bubbles up.

document.addEventListener('focusin', function(e) { console.log('focusin!')})

Demo: Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM