Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChristinaPolischuk/f248b25d3b0bbfdb86af2fc9aba877ca to your computer and use it in GitHub Desktop.
Save ChristinaPolischuk/f248b25d3b0bbfdb86af2fc9aba877ca 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment