On my page, I have multiple text boxes and need at least one of those boxes to always have focus. Is there a js event listener I can call that will detect when nothing on the page has focus, so I can give it focus?
Asked
Active
Viewed 563 times
1
-
Does this answer your question? [How do I find out which DOM element has the focus?](https://stackoverflow.com/questions/497094/how-do-i-find-out-which-dom-element-has-the-focus) – IceMetalPunk Jan 17 '20 at 19:06
-
1"need at least one of those boxes to always have focus" – That is not possible. Just select the address bar in your browser and any focused element will lose focus. – str Jan 17 '20 at 19:07
-
I currently have it set up that whenever anywhere on the page is clicked, the text box gets focus. However, there are many buttons that make ajax calls that then cause the page to have nothing focused. Now I could go to every ajax call and set focus to the box after each one, but I'm just wondering if there's something easier, to where I can just let the page recognize that nothing has focus, then in this case set the focus. – Afdufsko Jan 17 '20 at 19:24
3 Answers
2
If you want to know if an element from a list of tags is focused :
function hasFocus(selector) {
return Array
.from(document.querySelectorAll(selector))
.some(function(el){
return el === document.activeElement
});
}
// usage
console.log(hasFocus('input, select, textarea'))

wawan
- 497
- 6
- 11
0
You can also attach a focusout
handler to the document
which checks the focusable elements every time a focusout event bubbles up. Then force focus on an element other than the source of the blur event, if none have it.
Edited per comment.

varontron
- 1,120
- 7
- 21
-
blur event will not bubble up by default,change useCapture to true or use another event 'focusout' – MING WU Jan 17 '20 at 20:08
0
Please check out my solution on this link: https://codesandbox.io/s/nostalgic-lovelace-f9hei
When you load the page, the first input get focus. Everytime you click out. A random input get focused.
blur event will not bubble up by default. So make it bubble up by changing usecapture to true.
const inputs = document.querySelectorAll('input')
document.querySelector('input').focus()
document.addEventListener('blur', (e) => {
console.log(e)
if (e.isTrusted) {
const random = Math.round(Math.random() * (inputs.length-1));
console.log(random)
Array.from(inputs)[random].focus()
}
},true)

MING WU
- 2,962
- 1
- 12
- 16
-
Why do you focus on a random element? That doesn't makes too much sense to me... – FZs Jan 18 '20 at 15:37
-
The requirement of the question is that "at least one of those boxes to always have focus". I assume it means a random input needs to be focused. – MING WU Jan 18 '20 at 20:17