Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript / jQuery: Test if window has focus

How do you test if the browser has focus?

like image 405
Rod Avatar asked Aug 13 '10 18:08

Rod


People also ask

How do you check if an element is focused in JS?

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.

How do you know if input is focused?

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.

How do I check my browser focus?

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.

How do I check if a div is in focus?

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.


Video Answer


1 Answers

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); 
like image 158
gumape Avatar answered Sep 28 '22 08:09

gumape