Thomaszter
Thomaszter

Reputation: 1474

Trying to stop jQuery click event as long as animation works

I have a content slider, additionally I made "prev" & "next" buttons. The buttons should only be clickable when the animation is complete (animations duration is 500ms). I tried to solve it with the :animated selector, but it won't work:

if (!$(".scrollContainer").is(':animated')) {
    $(".nextItems a").click(function() {
        $(".slideNavig").find('a.selected').removeClass('selected').parent().next().find("a").addClass('selected');
    });
}
if (!$(".scrollContainer").is(':animated')) {
    $(".prevItems a").click(function() {
        $(".slideNavig").find('a.selected').removeClass('selected').parent().prev().find("a").addClass('selected');
    });
}

Or quite simply, I need to stop the buttons click event for 500ms after a click. Can anyone help me please?

Upvotes: 1

Views: 657

Answers (3)

Rafay
Rafay

Reputation: 31033

You can use .delay() (available in jQuery 1.4 and higher) or you can use .setTimeOut().

http://forum.jquery.com/topic/settimeout-15-6-2010

http://api.jquery.com/delay/

Upvotes: 0

PetersenDidIt
PetersenDidIt

Reputation: 25620

Move the if statement that checks if the thing is animated inside your click event handler:

$(".nextItems a").click(function() {
    if (!$(".scrollContainer").is(':animated')) {
        $(".slideNavig").find('a.selected').removeClass('selected').parent().next().find("a").addClass('selected');
    }
});

$(".prevItems a").click(function() {
    if (!$(".scrollContainer").is(':animated')) {
        $(".slideNavig").find('a.selected').removeClass('selected').parent().prev().find("a").addClass('selected');
    }
});

Also you could dry out your code by doing something like this:

$(".nextItems a").click(function() {
    nextPrevItem('next');
});

$(".prevItems a").click(function() {
    nextPrevItem('prev');
});
function nextPrevItem( direction ) {
    if (!$(".scrollContainer").is(':animated')) {
        $(".slideNavig").find('a.selected').removeClass('selected')
            .parent()[ direction ]()
            .find("a").addClass('selected');
    }   
}

Upvotes: 4

user113716
user113716

Reputation: 322492

You need the if statement inside the handlers:

$(".nextItems a").click(function() {
    if (!$(".scrollContainer").is(':animated')) {
        $(".slideNavig").find('a.selected').removeClass('selected').parent().next().find("a").addClass('selected');
    }
});

$(".prevItems a").click(function() {
    if (!$(".scrollContainer").is(':animated')) {
        $(".slideNavig").find('a.selected').removeClass('selected').parent().prev().find("a").addClass('selected');
    }
});

Upvotes: 2

Related Questions