How do you test if the browser has focus?
To detect if the element has the focus in JavaScript, you can use the read-only property activeElement of the document object. const elem = document. activeElement; The activeElement returns the currently focused element in the document.
To check if an input field has focus with JavaScript, we can use the document. activeElement property to get the element in focus. to add an input. to check if the input element is focused.
Use the visibilitychange event to detect if a browser tab has focus or not, e.g. document. addEventListener('visibilitychange', checkTabFocused) . The event is fired at the document when the contents of its tab have become visible or have been hidden.
hasFocus() The hasFocus() method of the Document interface returns a boolean value indicating whether the document or any element inside the document has focus. This method can be used to determine whether the active element in a document has focus.
use the hasFocus method of the document. You can find detailed description and an example here: hasFocus method
EDIT: Added fiddle http://jsfiddle.net/Msjyv/3/
HTML
Currently <b id="status">without</b> focus...
JS
function check() { if(document.hasFocus() == lastFocusStatus) return; lastFocusStatus = !lastFocusStatus; statusEl.innerText = lastFocusStatus ? 'with' : 'without'; } window.statusEl = document.getElementById('status'); window.lastFocusStatus = document.hasFocus(); check(); setInterval(check, 200);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With