Horen
Horen

Reputation: 11382

jQuery animate on blur - but only if blur outside of form

I have a search input (#search_input) which expands when being focused. Additional search options pop up that allow me to select specific search options.

The input should contract after it blurs, but only when the blur was triggered outside of the form.

http://jsfiddle.net/zMp9S/

Right now I'm using the following which contracts the search input too early even when I'm just choosing a an option from the search option menu:

$(function() {
    $("#search_input").focus(function(){
        $("#search_input").stop().animate({width: 310}, 200);
        $("#search_options").show();
    })
    $("#search_input").blur(function(){
        $("#search_input").stop().animate({width: 100}, 200);
        $("#search_options").hide();
    })        
});​

Putting focus / blur events on the form doesn't work.

How can I tell jQuery to only contract #search_input when the blur happens outside the form #search_form ?

Upvotes: 0

Views: 304

Answers (1)

VAShhh
VAShhh

Reputation: 3504

You must bind to the click event of the window, otherwise you'll be unable to detect if the user is losing the focus of a div (that actually does not have a focus/blur event!)

  $(window).click(function(e) {
        if (e.target.id != 'search_options' && e.target.parentNode.id != 'search_options' && e.target.id != 'search_input') {
            $("#search_input").stop().animate({
                width: 100
            }, 200);
            $("#search_options").hide();
        }
    });

http://jsfiddle.net/zMp9S/9/

Upvotes: 1

Related Questions