Search code examples
javascriptjqueryfirefoxfocusout

jQuery: Firefox focusout Event


I've got two input boxes in a div, I want to hide that div on the focusOut of the inputs, but only if both of them do not have focus.

This is a common Firefox problem (some call it adhering to standard), but the document body steals focus between.

HTML


<div id="baz">
   <input type="text" id="foo" name="foo" />
   <input type="text" id="bar" name="bar" />
</div>

jQuery


// jQuery Example
jQuery(":input").focusout(function(){
   // Don't do anything if one of the input boxes has focus
   if( jQuery(":input").is( jQuery(document.activeElement) ){ return; }

   // Hide the container if one of the inputs loose focus
   jQuery(this).parents("div").css("display","none");
}

Though this is a common bug, I forget how I solved it in the past. I think it had something to do with setting a timeout, or doing a screen refresh, before checking for the activeElement.


jsFiddle Example

jsFiddle Updated (FF4 Same Problem)


Solution

  • Demo

    jQuery(":input").focusout(function(){
        var elem = jQuery(this).parent("div");
        window.setTimeout(function(){
                // Don't do anything if one of the input boxes has focus
                if( jQuery(":input").is( jQuery(document.activeElement) )){ return; }
    
                // Hide the container if one of the inputs loose focus
                elem.hide();
        }, 0);
    })
    

    Demo

    jQuery(document).ready(function () {
        var timeoutID;
    
        jQuery(":input").focus(function () {
            window.clearTimeout(timeoutID);
        }).focusout(function () {
            timeoutID = window.setTimeout(function () {
                jQuery("#baz").hide();
            }, 0);
        });
    });