views:

28

answers:

2

Hi. I have this function, that adds 31px to my style bottom on ul. It works fine, but if I click fast, it no longer adds 31px, but some weird number like 17.423px. I guess it's because the animation isn't done, and thereby by clicking fast it adds 31px to the current px amount. My thought is that I need to insert a stop(). But where?

Thanks

$(function () {
        $('.topTenTwocolumns .topTenTwocolumnsWrap .down').click(function () {
            if ($("ul").css("bottom") !== '2728px') {
                $(this).parents('.topTenTwocolumnsWrap').children('ul').stop().animate({
                    bottom: '+=31'
                }, 200);
            }
        });
    });
A: 

The animations are queued, but it might be that the values to animate are calculated before the animation is queued, and as you are using a relative value it would calculate the animation from it current position.

You already have a stop call in the code. I don't know if you added that afterwards, otherwise that could also explain the values. If you stop the animation halfways, the bottom value will naturally be changed halfways.

You could keep the current target value in a variable so that you can specify an absolute value for the animation:

$(function () {

   var current = 0;

   $('.topTenTwocolumns .topTenTwocolumnsWrap .down').click(function () {
      if (current < 2728) {
         current += 31;
         $(this).parents('.topTenTwocolumnsWrap').children('ul').stop().animate({
            bottom: current + 'px'
         }, 200);
      }
   });
});

This way you can keep the stop call so that the new animation replaces the previous instead of being queued.

Guffa
You were right. The stop(), I had inserted did in fact cause the problem of the weird numbers.
Johansrk
A: 

I would probably try to prevent the function from firing if one is already in flight. Something like this might work:

$(function () { 
        $('.topTenTwocolumns .topTenTwocolumnsWrap .down').click(function () { 
            if ($(this).data('in_flight') === true){ 
                return false;
            } else {
                if ($("ul").css("bottom") !== '2728px') {
                    $(this).data('in_flight', true);
                    $(this).parents('.topTenTwocolumnsWrap').children('ul').stop().animate({
                        bottom: '+=31'
                    }, 200);
                    $(this).data('in_flight', false);
                }
            }
        });
    });

A more complicated approach would be to count the clicks and queue them (triggering the next one after the current running function completes). You could use similar code to do this.

samg