ahmed
ahmed

Reputation: 11

How to prevent multiple clicks using JavaScript or jQuery?

var slideContainer = ('#slider');  
var width = 720;

function slide () {  
  if ( parseInt( $slideContainer.css('marginLeft') ) >= -2160 ) {
    $slideContainer.animate({'margin-left': '-='+width},200);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class='button' onclick='slide()'></a>

I have this simple function, the problem is when I click multiple clicks on the button with animation speed more than 150 it take the slider container more to the left more than -2160 the limit in my if condition .

Upvotes: 1

Views: 1320

Answers (2)

Vishal Chaurasia
Vishal Chaurasia

Reputation: 98

You can achieve this in either ways-

  1. You can use flag variable to indicate that animation is still in process- initially set false then set true when animation starts and false on animation completion , use this flag with & expression in if.
  2. Little complex but still solves the purpose , you can try this- Inside function slide write the following snippet-

var events = $._data(sliderContainer[0], 'events');
                        handler = events.click;
                        events.click = null;

slideContainer.animate({'margin-left': '-='+width},{duration: 200, complete:function(){evends.click = handler }});

Hope this helps..

Upvotes: 0

Edwin.Tang
Edwin.Tang

Reputation: 21

var slideContainer = ('#slider');  
var width = 720;
var clicked = false;

function slide () {  
      if ( clicked ) return;
      clicked = true;
      if (parseInt( $slideContainer.css('marginLeft') ) >= -2160 ) {
        $slideContainer.animate({'margin-left': '-='+width},200,"linear",()=>{
clicked=false;});
       }
}
<a class='button' onclick='slide()'></a>

Upvotes: 1

Related Questions