How to create event listener on Window.Blur () event?
13,208
Solution 1
window.onblur = function() {
//say goodbye
};
According to quirksmode onfocus
and onblur
are available on the window
in most browsers.
Solution 2
It's better to use addEventListener
instead of a property, this way you can set multiple handlers and nobody (including yourself) will accidentally disable your handler by overwriting the onblur
property.
window.addEventListener('blur', function() {
console.log('blur');
});
Comments
-
Rella almost 2 years
Javascript: How to create event listener on
Window.Blur()
event? -
Jacob Mattison over 13 yearsOnly thing I'll add is that older version of Internet Explorer didn't handle this correctly; you can work-around using document.onfocusout.
-
Caleb Kleveter over 6 yearsWhile this code might answer the question, it is usually considered good practice to add an explanation of what your code does. This allows for developers who are not knowledgeable in this area to understand what is going on in the code and helps them to learn how to solve the problem by them selves in the future.