Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery $(window).focusout issue

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?

like image 236
Uriel Bertoche Avatar asked Feb 28 '11 14:02

Uriel Bertoche


2 Answers

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/

like image 64
Šime Vidas Avatar answered Nov 09 '22 22:11

Šime Vidas


Does this answer it? Talks about using blur event

JavaScript / jQuery: Test if window has focus

like image 44
jenson-button-event Avatar answered Nov 09 '22 22:11

jenson-button-event