简体   繁体   中英

How to allow only one JavaScript 'click' method to be clicked at a time while animation is executing?

When an element is clicked, a div slides off the screen into the center. When another element is clicked, other div in the center slides off the screen and another div slides in.

The issue occurs when another element is clicked before the initial div has the time to slide to the center of the screen.

$('#about').click(function(){
   /* makes any visible div slide out and slides in the 'about' div */ });

$('#contact').click(function(){
   /* makes any visible div slide out and slides in the 'contact' div */ });

In other words, when you click about and right away click contact then they both slide in inconsistently.

I already tried "attrRemove", "unbind", "off"... and although they work to disable clicks, I cannot enable them again.

One way you could approach this is through the use of a variable that indicates if an action is currently in effect. If you want to queue the event (so you don't entirely disregard the click (as the example below is doing), then the code could be modified to add it to a queue of some sort.

var slideInProgress = false;

$('#about').click(function(){
    if (!slideInProgress) {
        slideInProgress = true;
        $("#slider").slideToggle(5000, function(){
        slideInProgress = false;
    });
  }
});

A very simple, quickly put together Fiddle for this example is here: https://jsfiddle.net/t8tcr0rp/

This code may help.

function aboutFunc() {
  $('#about').off('click');
  $('#contact').off('click');

  //do your stuff

  $('#about').on('click', aboutFunc);
  $('#contact').on('click', contactFunc);
}

function contactFunc() {
  $('#about').off('click');
  $('#contact').off('click');

  //do your stuff

  $('#about').on('click', aboutFunc);
  $('#contact').on('click', contactFunc);
}


$('#about').on('click', aboutFunc);
$('#contact').on('click', contactFunc);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM