griegs
griegs

Reputation: 22760

jQuery hide div on focus out unless certain div is clicked

I have a div that is popped up as a list of items as you type into a text box.

On blur of the textbox I hide the list of items.

However, I have click events on the items that no longer trigger because the focusout event fires first.

What I want is to hide the list on blur unless an item in the list has been clicked.

Does anyone know of a way?

It should work the same as the Tags section of this site when asking a question.

Upvotes: 2

Views: 7922

Answers (2)

ElmosHomie492
ElmosHomie492

Reputation: 94

I'm working on a custom search engine for a web app that I'm building. This is the solution I came up with for a similar issue. It works in all browsers to the best of my knowledge.

$( document ).ready(function() {
    $( '#inputBox' ).focusout( function() {
        $( '#resultsDiv' ).hover(
            function() {         
                return;
            },
            function() {
                $( '#resultsDiv' ).fadeOut( 'slow' );
                $( '#resultsDiv' ).html( '' );
            });
    });
});

I changed the blur method to focusout (has to be all lowercase by the way...focusOut will not work). The .hover event has two conditions; true or false. The first function fires if it's true (if the user is hovering over the results) and the second function fires if the user is NOT hovering over the results.

The only "problem" I've had is that it fades out when the user goes outside of the #resultsDiv. I would add a little bit of clear padding around it to make sure the user doesn't go outside of it on accident.

Upvotes: 1

Paul
Paul

Reputation: 1947

With jQuery 1.6 or higher you can use the :focus selector to see if your div has any children that have focus before hiding the div.

$("#textboxID").blur(function () {
    if ($("#divID").has(":focus").length == 0) {  //if you click on anything other than the results
        $("#divID").hide();  //hide the results
    }
});

Update: Turns out that only worked in IE. Here is a better solution, though a little complex for the task. http://jsfiddle.net/cB2CN/

var resultsSelected = false;
$("#ResultsDIV").hover(
    function () { resultsSelected = true; },
    function () { resultsSelected = false; }
);

$("#TextBox").blur(function () {
    if (!resultsSelected) {  //if you click on anything other than the results
        $("#ResultsDIV").hide();  //hide the results
    }
});

Upvotes: 5

Related Questions