Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine whether the user has switched to another tab of the current browser [duplicate]

I wish to determine using jquery or javascript that is the user has switched tab standing on the same browser?

I.e. if the user is currently standing on browser say mozilla-firefox tab no.1 , now he has opened another tab say tab no.2 , at that point a popup should appear , with the message "tab changed"

like image 354
user1083472 Avatar asked Dec 02 '22 01:12

user1083472


2 Answers

I believe you can use the window.onblur event which will fire when the current page loses focus.

window.onblur = function() {
    // Your action here
};

In jQuery, you write it this way

$(window).blur(function() {
    // Your action here
});
like image 66
Liam Newmarch Avatar answered Dec 04 '22 09:12

Liam Newmarch


Without jQuery

window.onblur = function () {
    // do some stuff after tab was changed e.g.
    alert('You switched the tab');
}

with jQuery:

$('window').blur(function () {
    // do some stuff after tab was changed e.g.
    alert('You switched the tab');
});

Of course displaying alert is not best thing to do, because it focus current tab again :)

like image 45
Mateusz W Avatar answered Dec 04 '22 11:12

Mateusz W