jQuery fix click memorising

Viewed 46
$(".fsb").on("click", function () {
    if ($('.fsb').hasClass('fsbc')) {
        $('#sfo p').fadeIn(500);
        setTimeout(function () {
            $('#sfo p').fadeOut(500);
        }, 500);
    } else {
        $('#sfof p').fadeIn(500);
        setTimeout(function () {
            $('#sfof p').fadeOut(500);
        }, 500);
    }
});

After clicking many times on the button(fast), it will repeat hiding and unhiding that much times. I want to disable that but have no ideas.(sorry, I'm new to this).

1 Answers
  1. jQuery allows to use .fadeIn() and .fadeOut() in chain without setTimeout().
  2. To remove all queued animation place .stop(true) before them.
  3. Inside the event handler, you can use $(this) to work on the clicked element.

$(document).ready(function() {
  $(".fsb").on("click", function() {
    if ($(this).hasClass('fsbc')) {
      $('#sfo p').stop(true).fadeIn(500).fadeOut(500);
    } else {
      $('#sfof p').stop(true).fadeIn(500).fadeOut(500);
    }
  });
});
.hide-p p {
  display: none;
}
<button class="fsb fsbc">Click SFO</button>
<button class="fsb">Click SFOF</button>
<div id="sfo" class="hide-p">
  <p>SFO</p>
</div>
<div id="sfof" class="hide-p">
  <p>SFOF</p>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related