Javascript to detect if user changes tab


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.e if the person tries to see the answer from some other window/tab , quiz should stop.How can i do that?
P.S: it shouldn't be some very new HTML5 feature.I want it to be supported by all major browser currently.

Answers:

Answer

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

Answer

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

Answer

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

Answer

With jQuery:

$(window).on('focus', function () {

});

$(window).on('blur', function () {

});

$().focus & $().blur are deprecated.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.