I want to write a webpage for online quiz.Basic requirement i have is that, If the person taking quiz changes tab or opens new window even without minimizing browser, i.
In 2020 you can:
document.addEventListener("visibilitychange", event => {
if (document.visibilityState == "visible") {
console.log("tab is activate")
} else {
console.log("tab is inactive")
}
})
Best native function hands down, no jQuery.
document.hasFocus
Check the pen, check what happens when you go to the link and back to the codepen tab.
https://codepen.io/damianocel/pen/Yxxzdj
If you are targeting browsers that support it, you can use the Page Visibility API available in HTML5. It doesn't directly detect tab changes, per-say, but visibility changes. Which would include (but not limited to) tab changes.
See https://developer.mozilla.org/en/DOM/Using_the_Page_Visibility_API
You can determine if a tab or window is active by attaching a blur / focus event listener to window.
in jQuery it would be
$(window).focus(function() {
//do something
});
$(window).blur(function() {
//do something
});
quoted from this SO answer: https://stackoverflow.com/a/1760268/680578
With jQuery:
$(window).on('focus', function () {
});
$(window).on('blur', function () {
});
$().focus
& $().blur
are deprecated.