StackOverflow Question: Managing Animations

http://stackoverflow.com/questions/25514169/disable-hover-until-animation-is-complete

by klenwell

HTML

<div id="header">
  <h2>header</h2>
  <span>title 1</span>
  <span>title 2</span>
</div>
<div class="slider">slider</div>
<button>mouseover</button>

CSS

#header { background-color: #ccccff; width: 100px; }
#header span { display:none; background: white; }
.slider { background-color: #ff9999; width: 200px; }
button { margin-top: 12px }

JavaScript

var $header = $('#header'),
    $titles = $header.find('span'),
    $slider = $('.slider'),
    $switch = $('button');
  
function mouseOverAnimation() {
  var animationComplete = $.Deferred();
  
  $slider.animate({ width : 400 });
  $header.animate({ width : 300 }, function() {
    var titlesIn = $titles.fadeIn(200).promise();
    $.when(titlesIn).then(function() { animationComplete.resolve() });
  });
  
  return animationComplete;
}

function mouseOutAnimation() {
  var animationComplete = $.Deferred();
  
  $titles.fadeOut(500, function() {
    var part1 = $header.animate({ width : 100 }).promise();
    var part2 = $slider.animate({ width : 200 }).promise();
    $.when([part1, part2]).done(function() { animationComplete.resolve() });
  });
  
  return animationComplete;
}

$switch.on('click', function() {
  if ($switch.text() == 'mouseover') {
    $switch.prop('disabled', true).text('animating...');
    var animationComplete = mouseOverAnimation();
    $.when(animationComplete).then(function() {
      $switch.prop('disabled', false).text('mouseout');
    }); 
  }
  else if ($switch.text() == 'mouseout') {
    $switch.prop('disabled', true).text('animating...');
    var animationComplete = mouseOutAnimation();
    $.when(animationComplete).then(function() {
      $switch.prop('disabled', false).text('mouseover');
    }); 
  }
  else {
    console.warn('animation in progress');
  }
});

// Compare: http://jsfiddle.net/klenwell/q9s5voe3/2/