Matt Coady
Matt Coady

Reputation: 3856

jQuery Blur Animate and Click conflict

I've got a search bar that slides down and when hit a button and slides up when you blur the field. There's an issue however with clicking the button while the field is in focus. It'll trigger the slideup animation which will follow up with the slidedown animation when the first animation completes.

$('#button').click(function(){
    $('.bar').animate({
        marginTop: "0"
    }, function(){
        $('.bar input').focus();
    })
})

$('.bar input').blur(function(){
    $('.bar').animate({
        marginTop: "-2em"
    })
})

Here's an example.

http://jsfiddle.net/mattcoady/6ncER/1/

Opening the menu works fine and clicking in the white space works fine. Clicking button while the menu is open causes the animation to trigger after the first. How do I prevent this from happening?

Upvotes: 1

Views: 229

Answers (2)

Dan-Nolan
Dan-Nolan

Reputation: 6657

Use a class to designate whether the menu is up or down:

$('#button').click(function(){
    var $bar = $('.bar');
    var isUp = $bar.hasClass('up');
    var isAnimating = $bar.is(':animated');

    // Either this menu is already down or it's animating, 
    // so don't register the click
    if(!isUp || isAnimating) {
        return;    
    }

    // Slide down the menu 
    $bar.removeClass('up').animate({
        marginTop: "0"
    }, function(){
        $('.bar input').focus();
    })
})

Fiddle

Upvotes: 1

A. Wolff
A. Wolff

Reputation: 74420

You can just cancel logic if element is animated: {if i get what you are looking for?!}

DEMO

if($('.bar').is(':animated'))return;

Upvotes: 0

Related Questions