0

I want to show an alert box when browser loses focus. So here is my code:

$(window).blur(function(e) {
    alert("Your browser lost focus");
    e.stopPropagation();
});

However, the alert box keep pop up, say when I use Alt+Tab to switch to another window. Can anyone help telling me what is wrong?

Koby Douek
  • 16,156
  • 19
  • 74
  • 103
Xiaojun Chen
  • 1,222
  • 2
  • 12
  • 21

3 Answers3

4

Using $(window).blur - Once an alert window pops, the alert box itself is causing you to lose focus on your browser. This is highly unrecommended.

If you only want to test lose focus, you should use:

 console.log("Your browser lost focus");

Otherwise, do not expose this to the site users - it will cause an infinite loop of alert windows.

Koby Douek
  • 16,156
  • 19
  • 74
  • 103
  • 2
    ProTip: Get out of the habit of using `alert()` for debugging. You'll find `console.log()` and `console.error()` will make your life much better. https://developer.mozilla.org/en-US/docs/Web/API/Console – cloudworks Mar 20 '17 at 06:08
0

Try this instead

$('selector').on(eventType, function (event) {
  alert(('cancelable' in event));   //will return true
  alert(event.cancelable);      //will return true if event can be cancelled
  //NOTE: Firefox mistakenly always returns true
});
Ankit Kumar Gupta
  • 1,256
  • 1
  • 10
  • 23
0
TRY THIS DEMO, ALERT ON LOST FOCUS, WHEN LOST FOCUS TRIGGER OR CALL ANY ACTION

TRY THIS FIDDLE

Alfin Paul
  • 1,543
  • 14
  • 26