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?

有帮助吗?

解决方案

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

其他提示

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

DEMO

if($('.bar').is(':animated'))return;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top