Is It possible to detect when browser window Is active/inactive
I did try:
$(window).on('focus', function(){
console.log(1);
});
$(window).on('blur', function(){
console.log(2);
});
But it seems that it's working only when user will click the window. but showing 2 when user will click eg. browser address bar.
What I want to achieve is to detect when current tab is active one.
How to improve this code?
Active means when the tab is visible. But if you want to tell if the user's mouse is directly on the page, you could use this:
<html onmouseenter="document.getElementById('h1').innerHTML = 'active'"onmouseleave="document.getElementById('h1').innerHTML = 'not active'">
<body style="width:100%;height:100px">
<h1 id="h1">not active</h1>
</body>
</html>
EDIT: using the page visibility API:
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") {
hidden = "hidden";
visibilityChange = "visibilitychange";
}
else if (typeof document.mozHidden !== "undefined") {
hidden = "mozHidden";
visibilityChange = "mozvisibilitychange";
}
else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
}
else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
function handleVisibilityChange() {
if (document[hidden]) {
//Not visible, Do whatever
}
else {
//Visible
}
}
if (typeof document.addEventListener === "undefined" ||
typeof document[hidden] === "undefined") {
alert("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
}
else {
document.addEventListener(visibilityChange, handleVisibilityChange, false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With