0

I want to make an exam page, and not let the user visiting other pages until he submits it.

It seems like onunload and onbeforeunload are for cases where the user explicitly close the page. I was wondering if there is a trigger for the event when the page lose focus.

moonkey
  • 311
  • 3
  • 13
  • 1
    possible duplicate of [How to tell if browser/tab is active](http://stackoverflow.com/questions/1760250/how-to-tell-if-browser-tab-is-active) – Prusprus Jun 29 '15 at 17:19
  • possible duplicate of [Is there a way to detect if a browser window is not currently active?](http://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active) – Gert Grenander Jun 29 '15 at 18:58

2 Answers2

3

You can use the mouseleave event, like so:

$(document).on('mouseleave',function(){
console.log('mouse exited');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

which will trigger anytime the mouse leaves the window.

depperm
  • 10,606
  • 4
  • 43
  • 67
2

You can use the $(window).blur() event for that.

$(window).blur(function() {
    console.log("page left");
});

Or even better the page visibility check which you can find here: https://developer.mozilla.org/en-US/docs/Web/Guide/User_experience/Using_the_Page_Visibility_API

However, even when you show an alert, you won't be able to keep someone on your page. They can just checkbox the alert to not show again. What you could do is to notify them that the test will auto submit if they leave the tab which they probably won't want.

$(window).blur(function() {
    if(!confirm("Notice about leaving the page")) {
        if(!document.hasFocus()) {
            console.log("user left the page");
        }
    }
});
Sebastian Nette
  • 7,364
  • 2
  • 17
  • 17
  • Thanks! the .blur() is exactly what I wanted. But how can I check if they actually leaved or not, so I can disable the submit button? – moonkey Jun 29 '15 at 18:42
  • 1
    I have updated my answer. You are better off using a confirm dialog instead of an alert. If the user clicks on "dont show this message again" then the confirm will return false/null when the user leaves. So `!confirm("...")`will tell you if the user left or not. – Sebastian Nette Jun 29 '15 at 18:54