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');
});
Share:
13,208
Rella
Author by

Rella

Hi! sorry - I am C/C++ noobe, and I am reading a book=)

Updated on July 22, 2022

Comments

  • Rella
    Rella almost 2 years

    Javascript: How to create event listener on Window.Blur() event?

  • Jacob Mattison
    Jacob Mattison over 13 years
    Only 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
    Caleb Kleveter over 6 years
    While 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.