user9461375
user9461375

Reputation:

How do you use mouseleave in CSS?

It works with jQuery very well, but I want to remove jQuery and just use CSS transitions instead. I want a 3 second delay on mouseleave. How can I make this work with CSS?

var hoverTimeout;
$('#theDiv').hover(function() {
  clearTimeout(hoverTimeout);
  $(this).addClass('hovered');
}, function() {
  var $self = $(this);
  hoverTimeout = setTimeout(function() {
    $self.removeClass('hovered');
  }, 3000);
});
div {
  height: 100px;
  width: 100px;
  background-color: blue;
}

.hovered {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

<div id="theDiv"></div>

Upvotes: 3

Views: 48

Answers (1)

Temani Afif
Temani Afif

Reputation: 272891

Consider transition-delay only on the unhover state:

div {
  height: 100px;
  width: 100px;
  background-color: blue;
  transition:all 0s 3s;
}

div:hover {
  background-color: red;
  transition:all 0s;
}
<div id="theDiv"></div>

Upvotes: 5

Related Questions