window.onblur not working

Charles John Thompson III picture Charles John Thompson III · Apr 28, 2012 · Viewed 19.4k times · Source

I can't seem to get window.onblur to work properly.

window.onblur = console.log('blur');

When the listener is applied to the window, it just runs when the page is loaded, but not when the window looses focus.

Answer

Spudley picture Spudley · Apr 28, 2012

Ryudice has told you what to do, but didn't explain why it didn't work your way. Understanding the mechanics of it will help you work out how to proceed further.

The reason is that your original code is running the console.log('blur') command immediately, and using the return value of that call as the window onblur event.

The return value of console.log() varies between browsers, but for the sake of argument, lets say it returns a boolean true value. This means that your original code is the equivalent of writing this:

window.onblur = true;

Which clearly isn't going to work as you expect.

What you need is for window.onblur to be set to a function that will be called each time the onblur event is triggered. This is achieved by wrapping the code in a function() {}, as per Ryudice's answer.

You can also achieve it in simple cases by not supplying the brackets on the function name you want to call. But this method only works if you don't have any arguments you want to pass to the function, so wouldn't be suited to your console.log example.

Hope that helps. If you're still puzzled, there's lots of resources on the web. Try googling for phrases like "javascript passing functions as arguments", and see what comes up.