Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent click event in jQuery triggering multiple times

I have created a jQuery content switcher. Generally, it works fine, but there is one problem with it. If you click the links on the side multiple times, multiple pieces of content sometimes become visible.

The problem most likely lies somewhere within the click event. Here is the code:

$('#tab-list li a').click(
    function() {
        var targetTab = $(this).attr('href');
        if ($(targetTab).is(':hidden')) {
            $('#tab-list li').removeClass('selected');
            var targetTabLink = $(this).parents('li').eq(0);
            $(targetTabLink).addClass('selected');
            $('.tab:visible').fadeOut('slow',
                function() {
                    $(targetTab).fadeIn('slow');
                }
            );
        }
        return false;
    }
);

I have tried adding a lock to the transition so that further clicks are ignored as the transition is happening, but to no avail. I have also tried to prevent the transition from being triggered if something is already animating, using the following:

if ($(':animated')) {
    // Don't do anything
}
else {
   // Do transition
}

But it seems to always think things are being animated. Any ideas how I can prevent the animation being triggered multiple times?

like image 970
White Elephant Avatar asked Jun 18 '09 12:06

White Elephant


1 Answers

One idea would be to remove the click event at the start of your function, and then add the click event back in when your animation has finished, so clicks during the duration would have no effect.

If you have the ability to execute code when the animation has finished this should work.

like image 67
Brian Ramsay Avatar answered Sep 28 '22 00:09

Brian Ramsay