Have you ever wanted to know when a user switches away from your website’s tab?
You can easily detect this using JavaScript’s visibilitychange
event, which triggers when the visibility state of the web page changes (i.e., when the user switches tabs or minimizes the browser).
Here’s a simple example:
JavaScript
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
console.log('User has switched to another tab');
} else {
console.log('User is back on the tab');
}
});
Expand
document.visibilityState
: Returns ‘hidden
‘ when the user switches to another tab or minimizes the browser, and ‘visible
‘ when they come back.
You can use this to pause media, track user engagement, or optimize performance when the user is inactive.
That’s it! Simple, yet powerful for user interaction tracking.
Advertisements