javascript

Use jQuery to check if a tab is active/inactive

When using jQuery, it is possible to check if a tab is active or inactive. This can be done by using focus and blur events. By using these events, it is possible to determine if a tab is currently active or not. This can be useful when trying to determine if a user is currently on a specific tab.

var interval_val;
function setInterValId() {
    interval_val = setInterval(function(){
        console.log("print every second if tab is active");
    }, 1000);
}

$(window).focus(function() {
    if (!interval_val) {
        setInterValId();
    }
});

$(window).blur(function() {
    clearInterval(interval_val);
    interval_val = 0;
});

The above code sets up an interval that will print to the console "print every second if the tab is active" every second, provided the tab is in focus. If the tab is not in focus, the interval is cleared.

So from the above code example, It is clear that we can use the below code to run some Javascript code or function when the tab becomes active.

$(window).focus(function() {
    // Do something here...
});

And when the user leaves the specific tab in the browser you can run the below jQuery code.

$(window).blur(function() {
    // Do something here...
});

To run a specific function when a webpage finished loading, you can use:

$(window).on("load", function() {
    // Do something here...
});
Was this helpful?