Matte Crystal
Matte Crystal

Reputation: 87

Why is this jQuery animation getting longer on each activation?

I have a jQuery animation that rotates an object each time it's clicked. The animation goal is simple, when clicked rotate the object 360 degrees over a period of time. Then the next time it's clicked rotate it the other opposite direction 360 degrees.

My current code seems to do this well on the first two clicks but afterwards it starts spinning more times with each click.

I would like to know why this happens, how to fix it using the same general approach, and finally other suggestions on alternative ways to get the desired effect that may be easier, but please answer the original questions first.

The code can be seen at: codepen

The jQuery portion is displayed below:

var settingSpun = false;

$('#foo').on('click',function(){
  if(settingSpun == false){
    settingSpun = true;
    $('#foo').animate({  borderSpacing: -360 }, {
    step: function(now,fx) {
      $(this).css('-webkit-transform','rotate('+now+'deg)'); 
      $(this).css('-moz-transform','rotate('+now+'deg)');
      $(this).css('transform','rotate('+now+'deg)');
    },
    duration:'slow'
  },'linear');
  }
  else{
    settingSpun = false;
    $('#foo').animate({  borderSpacing: 360 }, {
    step: function(now,fx) {
      $(this).css('-webkit-transform','rotate('+now+'deg)'); 
      $(this).css('-moz-transform','rotate('+now+'deg)');
      $(this).css('transform','rotate('+now+'deg)');
    },
    duration:'slow'
  },'linear');
  }
});

Upvotes: 0

Views: 77

Answers (1)

alabusa
alabusa

Reputation: 44

Use unbind so it only fires once:

$('#foo').unbind().on('click',function(){})

Hope this helps

Upvotes: 2

Related Questions