Categories
JavaScript Answers

How to detect if user changes tab with JavaScript?

Spread the love

Sometimes, we want to detect if user changes tab with JavaScript.

In this article, we’ll look at how to detect if user changes tab with JavaScript.

How to detect if user changes tab with JavaScript?

To detect if user changes tab with JavaScript, we listen to a few events.

For instance, we write

window.onfocus = (ev) => {
  console.log("gained focus");
};

window.onblur = (ev) => {
  console.log("lost focus");
};

to set window.onfocus to a function that’s called when the tab is in focus.

And we set window.onblur to a function that’s called when the tab loses focus.

Conclusion

To detect if user changes tab with JavaScript, we listen to a few events.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *