Preventing Jquery .click toggle function from running over and over with excess clicking

Im building a .clicktoggle function in jQuery and for the life of me i can't get a .stop like effect on it, basically i don't want it to play over and over if mash clicked.

I want it to be applied the the function so its self contained, that's where im stuck.

JS fiddle link

    (function($) {
  $.fn.clickToggle = function(func1, func2) {
    var funcs = [func1, func2];
    this.data('toggleclicked', 0);
    this.click(function() {
      var data = $(this).data();
      var tc = data.toggleclicked;
      $.proxy(funcs[tc], this)();
      data.toggleclicked = (tc + 1) % 2;
    });
    return this;
  };
}(jQuery));

$('div').clickToggle(function() {
  $('.testsubject').fadeOut(500);
}, function() {
  $('.testsubject').fadeIn(500);
});

    <div class="clickme">click me fast</div>
<div class="testsubject">how do i stop it playing over and over if you click alot</div>

Toggle .click seems like something alot of people would use so i thought it might be useful to ask it here

Answers 1

  • var clicked = false;
    var doing = false;
    
    $(".clickme").click(function(e) {
      if (doing) {
        return;
      } else {
        doing = true;
      }
      doing = true;
      clicked = !clicked;
      if (clicked) {
        $('.testsubject').fadeOut(700, function() {
            doing = false
        });
      } else {
            $('.testsubject').fadeIn(700, function() {
            doing = false;
        });
      }
    });
    

    This example is a simple toggle which only allows you to click when it is not doing anything. I explained on IRC, but as an example here, the function only runs when doing is set to false, which only happens when it's set after fadeIn() or fadeOut's callback function thingymajigger.


Related Articles