Event when the user changes the browser tabs in javascript [duplicate]

I am looking for an event that fires whenever the user switches from the page to another tab and another event that fires when the user switches to the tab again.

document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        console.log('Tab is hidden');
    } else {
        console.log('Tab is visible');
    }
});