Mdd
Mdd

Reputation: 4400

jQuery animate, ignore additional clicks until animation is done

I created some script to show a list when a bolded title is clicked on, and hide that same list when another title is clicked on.

Is there a way for animate to ignore additional clicks while the animation is running?

Here is a fiddle that I created:

http://jsfiddle.net/VBh5f/

Here is the HTML:

<ul id="accordion" class="collapsible">
  <li class="main"><span>+</span> <b>Oil and Vinegar</b>
        <ul>
            <li>Extra Virgin Olive Oil</li>
            <li>Nut and Seed Oils</li>    
            <li>Balsamic Vinegar</li>
            <li>Wine Vinegar</li>
        </ul>
  </li>         
  <li class="main"><span>+</span> <b>Coffee and Tea</b>
        <ul>
            <li>Mariage Frères Tea</li>    
            <li>Peaberry&#039;s Coffee and Tea</li>
        </ul>
  </li>    
</ul>

Here is the JavaScript:

function show(i) {
  $('.main > ul:eq('+i+')').css(
    {
      display:'block'
    }
    ).animate(
    {
      opacity: 1
    },
    100,
    function() {
      $(this).parent().find('span').text('-');   
    }
  );
}

function hide(i) {
  $('.main > ul:eq('+i+')').css(
    {
      display:'none'
    }
    ).animate(
    {
      opacity: 1
    },
    100,
    function() {
      $(this).parent().find('span').text('+');   
    }
  );
}

function listControl(i, doWhat) {
  $('.main').each(function(index, elem) {
    hide(index); 
  });
  if (doWhat === 'showList') {
    show(i);
  }
}

function click() {
  $('.main').on('click', function() {
    if ( $(this).find('ul').css('display') === 'none' ) {
      listControl( $(this).index(), 'showList' );
    }
    else {
      listControl( $(this).index() );
    }
  });
}

$(document).ready(function() {
  click(); 
});

Here is the CSS:

ul {list-style:none;}
.main > ul {display:none;}

Upvotes: 1

Views: 152

Answers (2)

A. Wolff
A. Wolff

Reputation: 74420

Try this:

http://jsfiddle.net/VBh5f/10/

$('.main').on('click', function() {
        if($('#accordion ul').is(':animated')) return;
        if ( $(this).find('ul').css('display') === 'none' ) {
            listControl( $(this).index(), 'showList' );
        }
        else {
            listControl( $(this).index() );
        }
    });

Upvotes: 2

FLX
FLX

Reputation: 2679

You can just create a var :

isMoving = true;
if(!isMoving){
//your code
}

And after in the callback isMoving = false;

Upvotes: 2

Related Questions