user779444 user779444 - 4 years ago 255
Javascript Question

jQuery - raise event when focus leaves a group of controls

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

on all 3 inputs and checking if
is one of the 3 inputs but
of one control occurs before
on another so
is always empty.

Anyone has any idea how to get around this?

Answer Source

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) {
        timeoutID = null;

$("#TheSafeZone input").blur(function () {

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download