Human Code
Human Code

Reputation: 93

Setting timeout function to add a class for Jquery on hover function

When a user hovers on a div I add one class. After the hover is finished I remove the first class and add a different class. The problem is that I want to remove the second class after 1.5 seconds from adding it.

So far my code adds the classes, but does not execute function with timeout.

$('.portfolio-card').hover(function() { 
  $(this).addClass('hover') 
}, function() { 
  $(this).removeClass('hover');  
  $(this).addClass('hover-over', setTimeout(function() { 
    $(this).removeClass('hover-over'); 
  }, 1500));
})

Upvotes: 1

Views: 804

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337714

Your use of addClass() and setTimeout() isn't quite right. They need to be called separately. You also need to retain the reference to this in the outer event handler scope, as within the setTimeout() handler it will refer to the window, not the element which raised the event.

As a side note, it's better practice to use CSS's :hover selector where possible over JS. Therefore you can amend your code to just use mouseleave instead of hover(). Try this:

$('.portfolio-card').on('mouseleave', function() {
  var $el = $(this).addClass('hover-over');
  setTimeout(function() {
    $el.removeClass('hover-over');
  }, 1500);
})
.portfolio-card:hover {
  color: red;
}

.hover-over {
  background-color: #CCC;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="portfolio-card">
  Hover me
</div>

Upvotes: 2

Related Questions