简体   繁体   中英

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?

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');
    }   
}

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');
    }
});

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM