Skip to content

Instantly share code, notes, and snippets.

@mstfldmr
Created April 5, 2016 14:54
Show Gist options
  • Save mstfldmr/29e38eedc562b38e3b3806157cfdad20 to your computer and use it in GitHub Desktop.
Save mstfldmr/29e38eedc562b38e3b3806157cfdad20 to your computer and use it in GitHub Desktop.
'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 / Blur 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>
This sample demonstrates how to handle events when a window is focused or it loses focus.
Bu örnek bir bir pencereye odaklanıldığında veya başka pencere, uygulama, sekmeye odaklanıldığında oluşan olayların kullanımını gösterir.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment