TK123 TK123 - 1 month ago 14
Javascript Question

jQuery focusout event on form element is triggered even when child element is clicked

I want to trigger the focusout when the user is not focusing on the ENTIRE form element. But it shouldn't trigger when the user clicks on any of the form's inner elements like in this case the text field or the button. But it's being triggered regardless even though the event is bound to the entire form. How to resolve this?

http://jsfiddle.net/exutahfa/

HTML:

<form>
<input type="text" />
<button type="button">Click Me</button>
</form>


jQuery:

$('form').on('focusout', function() {
alert('focus out');
});

Answer

This happens because you are in-fact not focusing on the form, but rather on one of its child elements (input or button in your case). The focusout (or blur) event will bubble up to the form but is not triggered by it directly.

You might want to:

  1. capture blur events on form inputs
  2. see if another child element of the same form received focus
$('form').on('focusout', function () {
    var $elem = $(this);

    // let the browser set focus on the newly clicked elem before check
    setTimeout(function () {
        if (!$elem.find(':focus').length) {
            alert('focus out');
        }
    }, 0);
});

Working example on JSFiddle.

See how the form doesn't receive any focus in the linked fiddle: it it did, it would have been highlighted with a red border (see CSS definitions).