Source Source - 2 months ago 10
jQuery Question

How to stop repeat occurences of sliding up and down

I have a function that shows a form when you click on a checkbox, and hides it when you uncheck the box. The issue is if someone clicks rapidly multiple times on the checkbox, then it just keeps sliding up and down until the iterations are finished.

I have already tried using stop(true,true), and yes, this did fix it, but it also destroyed the flow of the sliding.

So the flow still needs to work how it is currently.

$('#billing_different').click(function(){
if($('#billing_different').is(':checked')) $('#checkout_address_billing').slideDown();
else {
$('#checkout_address_billing').slideUp();
}
});


I have it working here

https://jsfiddle.net/ebwok5rg/1/

Answer

This should be better:

$('#billing_different').click(function(){
    $('#checkout_address_billing').stop();
    if($('#billing_different').is(':checked') && $('#checkout_address_billing').is(':hidden')){
        $('#checkout_address_billing').slideDown();
    } else if(!$('#billing_different').is(':checked') && $('#checkout_address_billing').is(':visible')){
        $('#checkout_address_billing').slideUp();
    }   
});

This checks the state of the checkbox AND the element being hidden or shown. If you click the button a ton it will only finish on the last animation needed as well as lets the user click the checkbox as many times as they want.

https://jsfiddle.net/ebwok5rg/3/

Comments