-3

Is there any javascript library to detect whether the tab is in focus or not and then execute the code accordingly?

Daksh Shah
  • 2,997
  • 6
  • 37
  • 71

2 Answers2

4

By this code you can check whether the window is in focus or not:

window.addEventListener('focus', function() {
    document.title = 'focused';
});

window.addEventListener('blur', function() {
    document.title = 'not focused';
});

And other thing, you have to code it up yourself if you face problems ask a question and add the code you tried along with it

Update: There is a little problem with this and also with the other answer given, the problem is that just scrolling won't make it work. You will need to interact with the page to make it work. But the accepted answer given here might work for scrolling too

Community
  • 1
  • 1
Daksh Shah
  • 2,997
  • 6
  • 37
  • 71
2

You can possible do this with native JS code like:

window.onfocus = function() {
    console.log('focussed');
}

window.onblur = function() {
    console.log('blurred');
}
putvande
  • 15,068
  • 3
  • 34
  • 50