-1

I'm coding an online exam and I want to know when users leave the exam page and when they return to it again. I have

if(document.hasFocus()==false){
                $.ajax({
                type: "POST",
                url: 'submission.php',
                data: {status: 'Absent'},
                success: function(data)
               { alert("Hey, you!"); }
              });
              }

PHP puts the status update, Time and User Ip into a DB. But I'd like to log when they return to the exam so I can calculate the length of absence. Best I've come up with is

<script>
    setInterval(checkFocus, 2000); // updates DB and issues alert every 2 seconds

  function checkFocus()
    {
     if(document.hasFocus()){
        $.ajax({
                type: "POST",
                url: 'submission.php',
                data: {status: 'Present'},
                success: function(data)
               { alert("Good luck in the exam!"); }
              });
          }
     if(document.hasFocus()==false){
                $.ajax({
                type: "POST",
                url: 'submission.php',
                data: {status: 'Absent'},
                success: function(data)
               { alert("Hey, you!"); }
              });
              }
    }
</script>       

I will take the alerts out :) but this code updates the DB every 2 seconds even when user is staying on page. I just can't think of the logic/sequencing to ONLY update DB when user leaves page and returns.

Benjamin
  • 187
  • 3
  • 17
  • Would this solve your issue? https://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active – Peter Pajchl Mar 10 '21 at 16:46
  • I had seen that question and all the answers. I can't find a snippet that addresses my particular requirement, unfortunately. – Benjamin Mar 10 '21 at 16:55

1 Answers1

1

With regards to adjusting your solution, you'd need to track the previous state and then act only when there's a difference between that and the current state:

const checkFocus = (() => {
  let hadFocus = null;
  return () => {
    const hasFocus = document.hasFocus();
    if(hadFocus == hasFocus) return;
    hadFocus = hasFocus;
    if(hasFocus) {
      // Do something when page focus gained
    }
    else {
      // Do something when page focus lost
    }
  };
})();
setInterval(checkFocus, 2000);
Ouroborus
  • 16,237
  • 4
  • 39
  • 62
  • Thank you, @Ouroborus. Overnight I was thinking of declaring a var with 1/0 or true/false values and adding it to my if(document.hasFocus()) condition, but your solution is better and worked first time! I note the newer const and let syntax, and will try to make use of it in future. – Benjamin Mar 11 '21 at 11:55