6

I have 3 textboxes within a div and I need to raise an event when focus leaves one of those inputs and doesn't go to another one of these 3 inputs.

As long as the user is editing one of these 3 controls, the event wont raise. The event will only raise when the focus has changed to a control which isn't one of these inputs.

I tried using focusout on all 3 inputs and checking if document.ActiveElement is one of the 3 inputs but focusout of one control occurs before focusin on another so document.ActiveElement is always empty.

Anyone has any idea how to get around this?

JunoPatch
  • 5
  • 3
user779444
  • 1,365
  • 4
  • 21
  • 38

2 Answers2

10

I would consider using a timer to solve this tricky dilemma.

When focus is lost, start the timer. Then you can cancel the timer if focus is then set upon another "safe" input.

Something like this:

var timeoutID;

$("#TheSafeZone input").focus(function () {
    if (timeoutID) {
        clearTimeout(timeoutID);
        timeoutID = null;
    }
});

$("#TheSafeZone input").blur(function () {
    releaseTheHounds();
});

function releaseTheHounds() {
    timeoutID = setTimeout(function () {
            alert("You're all going to die down here");
    }, 1);
}

Here is a working example

NOTE: I have set the timeout to just 1ms, this seems to work reliably for me but it may be worth doing a few tests in other browsers (I am using Chrome). I guess it is down to how the JS engine handles events, but I don't know enough about that to confidently say all browsers will work the same

musefan
  • 47,875
  • 21
  • 135
  • 185
  • One of the best answers I have gotten. – user779444 Jul 05 '13 at 13:23
  • I have a similar requirement where i am building custom autocomplete control. using Timeout was my last approach. I want to know can this be done without using timeouts – Goutham ܢܢ Jul 17 '14 at 05:28
  • @Gouthamܢܢ: erm, probably. Perhaps you would need to add a click/focus event to every single element in your page and check to see if it move from 1 textbox to another... not sure that's going to be better than a timer though, but I can understand your hesitation to use timers - it does seem a bit suspect – musefan Jul 17 '14 at 08:09
0

Put "Blur" and "Focus" events with opposite logic so that when ever user leaves group of controls specified in DIV only "Blur" event will be fired.

$(document).on("blur","#edit-area .form-control", function (event) {
      $('.editButtons').show();

  });
  $(document).on("focus","#edit-area .form-control", function (event) {
      $('.editButtons').hide();

  });
Zain
  • 1,226
  • 1
  • 16
  • 26