6

The problem is, I'm making a program like a chat, that needs to know if the user has left the window, or changed to another window or tab, to allow other users see that the other user is not seeing the page right now.

I thought the window event focusout would solve my problems, however, there are a few issues with it.

First:
it does not fire only when the user leaves the window, if they focus on a input field then click anywhere else in the page, the event fires. Obviously that's intolerable.

I managed, in Firefox, a way around that. On Firefox, when that happens, the browser fires the focusout event once. If you really leave the window however, it fires it twice. So, a little programming made the magic.

Then came the second problem:
Chrome, and I believe other browser might behave the same, only fires focusout event once, no matter what you do. Leaving the window, changing focus from inputs to page, it's the same, so, my programming didn't worked there.

Does anyone know a way to simulate the desired behavior? Or a way to make Chrome and other possible browser to behave like Firefox or whatever?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Uriel Bertoche
  • 883
  • 2
  • 13
  • 23

3 Answers3

10

Use blur instead of focusout:

$(window).blur(function() {
    // code
});

The difference is that focusout bubbles up the DOM tree and blur doesn't. If you set focusout on the window object, then all the blur events that occur on page elements will also trigger that handler which is something that you don't want.

The difference is that focusout (when set on the window object) captures all blur events that fire on the page (at any element). In contrast blur (when set on the window object) does not capture those blur events.

Live demo: http://jsfiddle.net/simevidas/taRG6/

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • I thought that jQuery would already use blur for Firefox and Chrome and focusout form IE, that seemed to be an issue with that. – Uriel Bertoche Feb 28 '11 at 15:13
  • @Uriel focusout and blur are two different event types (both defined in the [DOM 3 Events spec](http://www.w3.org/TR/DOM-Level-3-Events/)). jQuery does not mix them together. – Šime Vidas Feb 28 '11 at 15:29
1

Does this answer it? Talks about using blur event

JavaScript / jQuery: Test if window has focus

Community
  • 1
  • 1
jenson-button-event
  • 18,101
  • 11
  • 89
  • 155
0

I answer the question, this solution works perfectly except that i catch the event twice.

BLUR event on window is fired only when i click another brower tab or when i switch to another application.