Liam
Liam

Reputation: 9855

Prevent function running for lots of clicks

Sorry for the misleading title its hard to explain!

Basically I have a function that when you click left/right a div moves X pixels either way.

// Upcoming events slide 
$('.nextEvent').click(function(e){
    e.preventDefault();
    if($('.newsColWrap').offset().left == '597.5'){

    } else {
        $('.newsColWrap').stop(true,true).animate({'left' : "-=435px"},500)
    }
});
$('.prevEvent').click(function(e){
    e.preventDefault();
    if($('.newsColWrap').offset().left == '1032.5'){

    } else {
        $('.newsColWrap').stop(true,true).animate({'left' : "+=435px"},500);
    }
});

The function works fine, but if the animations is happening and you click again, because the if statement doesn't return my div moves too far, does this make sense?

Upvotes: 0

Views: 47

Answers (3)

kartikluke
kartikluke

Reputation: 2405

You could use a simple setTimeout function running for 500.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

The problem could be that you are reading the offset before the previous animation is completed so try

$('.nextEvent').click(function (e) {
    e.preventDefault();
    var $newsColWrap = $('.newsColWrap').stop(true, true);
    if ($newsColWrap.offset().left == '597.5') {

    } else {
        $newsColWrap.animate({
            'left': "-=435px"
        }, 500)
    }
});
$('.prevEvent').click(function (e) {
    e.preventDefault();
    var $newsColWrap = $('.newsColWrap').stop(true, true);
    if ($newsColWrap.offset().left == '1032.5') {

    } else {
        $newsColWrap.stop(true, true).animate({
            'left': "+=435px"
        }, 500);
    }
});

Upvotes: 1

techfoobar
techfoobar

Reputation: 66663

You can check if the element is being animated using :animated before animating it again.

$('.nextEvent').click(function(e){
    e.preventDefault();
    if($(this).is(':animated')) return; // check if currently being animated
    // ... animate
});

$('.prevEvent').click(function(e){
    e.preventDefault();
    if($(this).is(':animated')) return; // check if currently being animated
    // ... animate
});

Upvotes: 2

Related Questions