0

I want to prevent a second click from firing until an animation is complete.

$('#moveDown').click(function(){
  var currentPos = parseInt($('#blog-slider').css('top'));
  if (currentPos < 0) {
    $('#moveDown').unbind('click');
    $('#blog-slider').animate({'top': currentPos + 140},500, function() {
      $('#moveDown').bind('click');
    });
  }
});

Unbind is working fine, but it is not rebinding when the animation is complete, so the animation will only run once.

I did look here but this only confirms that "bind" and "unbind" is the way to get the functionality I need and I still don't understand why it isn't working.

Community
  • 1
  • 1
HelloWorld
  • 2,199
  • 3
  • 22
  • 36

1 Answers1

3

$('#moveDown').bind('click') just triggers a click, unless you bind a function that does something.

One technique is to set and unset a .data variable on the element, and check if it's set or not:

$('#moveDown').click(function(){
    if (!$('#moveDown').data('clicked')) {
        $('#moveDown').data('clicked',true);
        var currentPos = parseInt($('#blog-slider').css('top'),10); // always use a radix
        if (currentPos < 0) {
            $('#blog-slider').animate({'top': currentPos + 140},500, function() {
                $('#moveDown').data('clicked',false);
            });
        }
    }
});
Blazemonger
  • 82,329
  • 24
  • 132
  • 176
  • This is a good solution, but is there a way to rebind the click envent? I tried naming the function and binding click to the name of the function but that seems to make it try to run twice. However using "data" does solve the problem. – HelloWorld Sep 29 '14 at 20:51
  • Just don't unbind it in the first place. You don't really want to anyway, you just want to prevent it from running. – Blazemonger Sep 29 '14 at 20:52
  • Alright I will keep that in mind and research why that is. Thanks! – HelloWorld Sep 29 '14 at 20:55