How to check if a window has focus?

I'm trying to do something like this ...

if (window.onblur) { setTimeout(function () { DTitChange(name) }, 1000) } else { document.title = dtit } 

Window.onblur doesn't seem to work, is there something I can replace?

+4
source share
2 answers

What do you mean doesn't seem to work? Here is what you are saying now:

 If there an onblur event handler: execute DTitChange once ever second. Else document.title = dtit 

Most likely, this is not what you want. Try

 window.onblur = function () { setTimeout(function () { DTitChange(name) }, 1000); }; 

also make sure you set the onfocus handler to clear the timeout if you want it to stop when the user returns. :)

+1
source

You should assign a window.onblur function, in your question you only check if the onblur property onblur . But window.onblur does not always work correctly in every browser. The Focus Detection Browser Window article shows how to set it. In your case, it will be something like:

 function DTitBlur() { /* change title of page to 'name' */ setTimeout(function () { DTitChange(name) }, 1000); } function DTitFocus() { /* set title of page to previous value */ } if (/*@ cc_on!@ */false) { // check for Internet Explorer document.onfocusin = DTitFocus; document.onfocusout = DTitBlur; } else { window.onfocus = DTitFocus; window.onblur = DTitBlur; } 
0
source

Source: https://habr.com/ru/post/1314782/


All Articles