javascript – Canceling fadeOut () when hovering over a block

Question:

There is a code:

$('.button').on('click', function() {
  $('.response').text('Success');
  if ($('.response').fadeIn()) $('.response').delay(1000).fadeOut();
});
.button {
  width: 100px;
  height: 20px;
  background: gray;
}

.response {
  display: none;
  width: 100px;
  height: 100px;
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">Click Me</div>
<div class="response"></div>

How do I make the animation cancel when hovering over the .response block, and as soon as the mouse is out of bounds .response .fadeOut() fires?

Answer:

Use setTimeout () and clearTimeout () for this:

var timeout;
$('.button').on('click', function() {
  $('.response').text('Success');
  $('.response').fadeIn();
  timeout = setTimeout(function() {
    $('.response').fadeOut();
  }, 1000);
});

$('.response').on('mouseover', function() {
  clearTimeout(timeout);
}).on('mouseout', function() {
  timeout = setTimeout(function() {
    $('.response').fadeOut();
  }, 1000);
});
.button {
  width: 100px;
  height: 20px;
  background: gray;
}

.response {
  display: none;
  width: 100px;
  height: 100px;
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">Click Me</div>
<div class="response"></div>
Scroll to Top
AllEscort