Detecting focus of a browser window

Detecting focus of a browser window

How to make JavaScript detect if the browser is minimized or in the background. more >>

Contents

The JavaScript Code

function onBlur() {
//window is blurred
};

function onFocus(){
//window is focused
};

if (/*@cc_on!@*/false) { // check for Internet Explorer
document.onfocusin = onFocus;
document.onfocusout = onBlur;
} else {
window.onfocus = onFocus;
window.onblur = onBlur;
}

A Demo Page

Create a HTML file and put the following code inside:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">

function onBlur() {
document.body.className = 'blurred';
};
function onFocus(){
document.body.className = 'focused';
};

if (/*@cc_on!@*/false) { // check for Internet Explorer
document.onfocusin = onFocus;
document.onfocusout = onBlur;
} else {
window.onfocus = onFocus;
window.onblur = onBlur;
}

</script>
<style type="text/css">
.focused #focused, .blurred #blurred { display: block; font-size:48pt; }
.focused #blurred, .blurred #focused { display: none }

.focused {
background: white;
color: black;
}

.blurred {
background: black;
color: white;
}

</style>
</head>
<body class="focused">


<div>The window is currently</div>

 <div id="focused">FOCUSED</div>
 <div id="blurred">BLURRED</div>.

</body>
</html>


If you open the file in a browser, you should see something like on the image.

Change focus

Open any other application and set the focus to the window of it.
The browser now shows that its window is blurred.