0

If user switches tab in the browser, and comes back to the application tab I want to alert the user. I have written following code:

$(function () {
            $(window).focus(function () { alert("hi")  });
        });

The above code runs fine when user gets focus in his application tab, but when I tried to click on OK button of alert box, it again calls the focus event. So jQuery considers messagebox as a different tab other than the current tab, and alert is getting called again and again.

How to call alert only once when user gets focus on tab?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
ghanshyam.mirani
  • 3,075
  • 11
  • 45
  • 85
  • `so jquery considers messagebox as a different tab other than the current tab` Not quite. It's because clicking the `button` element also causes a `focus` event on the button, which then bubbles up the DOM to the `window` where you catch it again. – Rory McCrossan Jul 10 '17 at 07:43
  • Try attaching `focusin` and `focusout` and set a global variable within `focusin` and check for global variable and change its value accordingly.. – Guruprasad J Rao Jul 10 '17 at 07:45
  • Came across this, might be helpful: https://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active – Milan Chheda Jul 10 '17 at 07:45

0 Answers0