MJ Sabri
MJ Sabri

Reputation: 477

alert() function is looping when called in focus() event

I Want an Alert pop-up when focusing on input. It pops up correctly but when I click on 'OK' or 'x' i.e cancel, it Loops infinitely and never closes.

$('input').focus(function () {
       alert('hello');
});

Upvotes: 2

Views: 1691

Answers (2)

Alex Bass
Alex Bass

Reputation: 2432

This is because the input is assuming the focus again when the alert is closed (which is the new focus when it appears - notice the outline around the button in the dialogue?)

If you only want to make the alert show once, you could perhaps write something a resembling this:

let hasShownAlert = false

$('input').focus(function () {
  if (!hasShownAlert) {
    hasShownAlert = true
    alert('hello')
  }
})

Of course you could improve this with state containers or something, but this is the simplest way you could achieve it. (Note: the hasShownAlert variable has to be defined outside of the onfocus handler, otherwise it'll be cleared up by the garbage collector.)


Updated: So if you don't want it to only show once, there are a couple of things you could do. The first, the simpler, would be listening for the click event, rather than focus. The second way could be setting a didShowAlert variable -- inverting the value each time the handler is fired. E.g...

let didShowAlert = false
$('input').on('focus', (ev) => {
   if (didShowAlert) {
     didShowAlert = false
   } else {
     didShowAlert = true
     alert('hello')
   }
})

Upvotes: 2

Manav
Manav

Reputation: 1367

You could try a hack like

$(document).on("focus", 'input:not(.unFocus)', function() {
       alert('hello');
       $('input').addClass('unFocus');
       setTimeout(function() {
           $('input').removeClass('unFocus');
       }, 10);
});

It may not be the ideal way to do it, but it works :)

Upvotes: 0

Related Questions