Search code examples
jquerydelayfadeout

How to restart jquery delay.fadeout


When a user clicks a button, we do a

$('#element').show().delay(5000).fadeOut();

If they click the button within 5 seconds, we would like to restart the effect, but as it is written now, the first one completes and the second effect does not happen.


Solution

  • You can use finish() to make the previous action play to completion immediately. Ref. http://api.jquery.com/finish/

    $('#target').on('click', function(){
      $('#element').finish().show().delay(5000).fadeOut();
    });
    #element {
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="target">Do It</button>
    <div id="element">Element</div>