I'm currently trying to create a little animation when hovering a div using .animate()
jQuery function.
If you take a look at the code snippet, you will see that there is a very strange delay between the time your mouse leave the div and the animation is launch.
It's definitely something with .animate()
function because, there is a console.log
that is displayed when the mouse leave the div and without any strange delay.
Did I miss something or... Any ideas will be appreciate!
Thanks!
$(document).ready(function() {
$(".square").hover(function() {
var _this = this;
$(_this).find(".square-hover").eq(0).animate({
top: "0px",
}, 750)
})
$(".square").mouseleave(function() {
var _this = this;
console.log("mouseleave triggered");
$(_this).find(".square-hover").eq(0).animate({
top: "-300px",
}, 100)
});
})
.square {
box-shadow: 0 2px 2px 0 rgba(0,0,0,0.14), 0 1px 5px 0 rgba(0,0,0,0.12), 0 3px 1px -2px rgba(0,0,0,0.2);
padding: 0;
border: 1px solid rgba(255, 255, 255, 0.1);
height: 200px;
-webkit-transition-property: background-color;
-webkit-transition-duration: 0.2s;
overflow: hidden;
margin-top: 5px
}
.square-hover{
position: absolute;
top: -300px;
width: 100%;
height: 100%;
background-color: rgba(29, 233, 182, 0.85);
}
<script src="http://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-xs-6 col-xs-offset-3 square">
<div class="square-hover"></div>
</div>
The issue is because you're using hover
and mouseleave
. The hover
event handler is actually separate mouseenter
and mouseleave
handlers - so you're actually attaching 1 mouseenter
and 2 mouseleave
. This is the cause of your issue.
If you change the code to pass two functions to hover
(the first for mouseenter
, second for mouseleave
) your code works:
$(".square").hover(function() {
$(this).find(".square-hover").eq(0).stop(true).animate({
top: "0px",
}, 750)
}, function() {
$(this).find(".square-hover").eq(0).stop(true).animate({
top: "-300px",
}, 100)
});
Also note the use of stop(true)
in the above to prevent successive events clogging up the animation queue.