7

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.

Anders
  • 8,307
  • 9
  • 56
  • 88
CJT3
  • 2,788
  • 7
  • 30
  • 45

3 Answers3

25

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.

Spudley
  • 166,037
  • 39
  • 233
  • 307
24
window.onblur = function() { console.log('blur'); }
ryudice
  • 36,476
  • 32
  • 115
  • 163
  • 7
    Now... how do I get it to work if the user switches tabs or clicks in the address bar? – CJT3 Apr 28 '12 at 06:31
  • @CharlesJohnThompsonIII I think this might do the trick, but you may well have forgotten all about it by now. I had a similar problem and this was my solution for now. – Steve Jan 23 '16 at 02:13
  • 1
    @CharlesJohnThompsonIII Checkout the Page Visibility API on MDN. the `visibiltychange` event might be what you're looking for. – Govind Rai Feb 26 '18 at 19:51
1
window.onblur = () => console.log( "blur" );
karkael
  • 431
  • 2
  • 9
  • 7
    @FlorianEck Yes it will, that's just an [arrow function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions), it's a standard part of JavaScript (added in ES6, 2015). – Nebula Dec 03 '16 at 03:11