开发者

jQuery - How to remove event handler only while an animation or function is running?

开发者 https://www.devze.com 2023-01-10 23:08 出处:网络
I am attempting to create an image gallery. At the bottom I have a strip of thumbnails these thumbnails slide left and right when you click an arrow but开发者_开发知识库 if you click the arrow multipl

I am attempting to create an image gallery. At the bottom I have a strip of thumbnails these thumbnails slide left and right when you click an arrow but开发者_开发知识库 if you click the arrow multiple times it ques the function.

I would like to remove the click handler while the function is run, then replace it again.

On a side note, my thumbnail scroller uses margin-left to animate, is it possible to use scrollTo or similar, to move an element a specific amount, horizontally, so if the thumbnails change size, it would still work?


There are many ways to do this. The easiest way is not to remove the click handler, but simply do nothing in the callback if it's animating already, eg:

$('.thumb').click(function() {
    if ($('#thumb-strip:animated').size() != 0)
        return;

    /* else animate #thumb-strip */
});

If you want to remove the click handler, and add it before, just do this:

var animateHandler = function() {
    var params = {}; // animate params
    $('.thumb').unbind('click', animateHandler); // unbind the click handler
    $('#thumb-strip').animate(params, function() {
        $('.thumb').click(animateHandler); // re-bind the click handler when animation is done
    });
};
$('.thumb').click(animateHandler);

Needless to say, the first way is simpler.

However what I usually do is not prevent the click event from happening, because the user won't expect that, but I also want to get rid of the queuing of animations. So what you can do is allow the user to click a thumb, and make it instantly animate to the new place with stop:

$('.thumb').click(function() {
    var params = {}; // animate params
    $('#thumb-strip').stop().animate(params);
});

This is the simplest and most intuitive solution.

And to answer your second question, you can use $(this).position() to get the thumb's relative position to the parent, and then animate based on that.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号