Search code examples
javascriptjqueryconfirm

JavaScript confirm on blur/focusout event caught in endless loop on some OS's


I have this jsfiddle of a JavaScript confirm box. Here's the snippet as well:

$('#txtTestOne, #txtTestTwo').on('blur', function(e) {
  var retval = confirm('Do you really want to go there?');
  if (!retval) {
    e.target.focus();
  } else {
    e.relatedTarget.focus();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="text" id="txtTestOne" autofocus>
<input type="text" id="txtTestTwo">

This works fine on my laptop (OS X 10.6.8), tested in both Chrome and Opera. However, when I test it on my desktop machine running OS X 10.11.6, I find that the confirm box gets caught in an endless loop, both in Chrome and Safari (keeps re-displaying the window after making a selection).

I added the snippet in as well, to make sure that it wasn't a problem with jsfiddle, and no, it isn't. Same behavior both for the snippet and jsfiddle.

Since the problem exists in two different browsers on one OS, and doesn't in two browsers on another, it seems unlikely that it's a browser issue. I don't think I'm doing anything wrong with the code, either, but one never knows until one knows.

Am I doing something wrong, or is there some sort of problem with the confirm method that I don't know about? Also, if it runs correctly on your machine, perhaps you'll be so kind as to mention in the comments what OS you're running.


Solution

  • It seems I have found a solution. If you have a clearer picture than I do of why we have to do this, please explain.

    $('#txtTestOne, #txtTestTwo').on('blur', function(e) {
      if (!$(e.relatedTarget).is(':text')) {
        return;
      }
    
      var retval = confirm('Do you really want to go there?');
      if (!retval) {
        e.target.focus();
      } else {
        e.relatedTarget.focus();
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <input type="text" id="txtTestOne" autofocus>
    <input type="text" id="txtTestTwo">