Reputation: 45
How I can detect when user focus
in this tab and when user unfocus current tab
I'm trying this code:
window.onfocus = function() {
alert('Got focus');
}
Why this not work?
Upvotes: 2
Views: 7520
Reputation: 5658
This IS the API for tracking when the current tab gains or loses focus. You can spell it like so, and it will work for almost all browsers. I suggest using the following syntax:
window.addEventListener('focus', function(e){
console.log('Focused');
})
window.addEventListener('blur', function(e){
console.log('Unfocused');
})
One reason I can think of for not firing the event is that you're mostly sitting in your browser console. Window does not receive focus or blue events if the dev tools are what you've actually "focused".
Upvotes: 0
Reputation: 1081
For particular HTML element.....
$("#elementId").focus(function(){
//fire when element is focused...
});
$("#elementId").blur(function(){
//fire when element is unfocused...
});
For window.....
$(function() {
$(window).focus(function() {
console.log('Focus event');
});
$(window).blur(function() {
console.log('un focus');
});
});
Upvotes: 0
Reputation: 3516
The event you are looking for is visibilityChange
https://developer.mozilla.org/en-US/docs/Web/Events/visibilitychange
When the event if fired, you can check if the page is visible or not through document[hidden]. See https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API for a working example.
Upvotes: 4