Skip to content

Instantly share code, notes, and snippets.

@RunnerRick
Last active November 27, 2023 11:27
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save RunnerRick/7645270 to your computer and use it in GitHub Desktop.
Save RunnerRick/7645270 to your computer and use it in GitHub Desktop.
Demonstrates how to handle the window's `focus` and `blur` events.

Demonstrates how to handle the window's focus and blur events.

This code does not depend on any third-party libraries like jQuery.

'use strict';
// Create `myApp` namespace.
window.myApp = {
// Function to use for the `focus` event.
onFocus: function () {
// Append message to the `body` element.
document.body.appendChild(
document.createTextNode('The window has focus.'));
// Add a line break.
document.body.appendChild(document.createElement('br'));
},
// Function to use for the `blur` event.
onBlur: function () {
// Append message to the `body` element.
document.body.appendChild(
document.createTextNode('The window has lost focus.'));
// Add a line break.
document.body.appendChild(document.createElement('br'));
}
};
/* Detect if the browser supports `addEventListener`
Complies with DOM Event specification. */
if(window.addEventListener) {
// Handle window's `load` event.
window.addEventListener('load', function () {
// Wire up the `focus` and `blur` event handlers.
window.addEventListener('focus', window.myApp.onFocus);
window.addEventListener('blur', window.myApp.onBlur);
});
}
/* Detect if the browser supports `attachEvent`
Only Internet Explorer browsers support that. */
else if(window.attachEvent) {
// Handle window's `load` event.
window.attachEvent('onload', function () {
// Wire up the `focus` and `blur` event handlers.
window.attachEvent('onfocus', window.myApp.onFocus);
window.attachEvent('onblur', window.myApp.onBlur);
});
}
/* If neither event handler function exists, then overwrite
the built-in event handers. With this technique any previous event
handlers are lost. */
else {
// Handle window's `load` event.
window.onload = function () {
// Wire up the `focus` and `blur` event handlers.
window.onfocus = window.myApp.onFocus;
window.onblur = window.myApp.onBlur;
};
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Window Focus Example</title>
</head>
<body>
<p>Click anywhere in the browser's viewport to trigger the <code>focus</code> event.</p>
<p>Click on something other than the browser's viewport to trigger the <code>blur</code> event.</p>
<script src="app.js"></script>
</body>
</html>
@JBarna
Copy link

JBarna commented Aug 4, 2015

This is great. Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment