How do I detect if the browser window is active

The code im currently using is this

var focus;
function focuswindow() { focus = true; }
function hidewindow() { focus = false; }
window.onfocus = focuswindow();
window.onblur = hidewindow();

The idea is that it can be used like this

if( focus ) { //do something
}

However its not working. Also it only needs to work on Chrome (so no legacy IE stuff) since its for a Chrome extension.

Answers


The reason it doesn't work is that you're calling the functions immediately and assigning the return value of undefined to onfocus and onblur.

Instead, onfocus and onblur should reference the functions by name.

Try this:

window.onfocus = focuswindow;
window.onblur = hidewindow;

Notice that I removed the () call operators. Now onfocus and onblur are referencing the functions, and will call them when the events occur.


Need Your Help

PHP File Upload Undefined Index error

php jquery ajax forms file-upload

I'm extremely confused by this. I have a form in which a user has the option to upload a resume... easy enough.

Division in x86 Assembly GAS

assembly x86 att

Im not quite sure yet how division works in x86 assembly (GAS AT&T syntax). What i wanna do is to divide two longs, and then multiply the quotient with the divisor to see if the new number is e...