Inside a div .frame I have 3 others div: .top
, .middle
and .bottom
.
.top
and .bottom
are in display none
, and when the mouse is over .frame
, with the jquery function animate
, the height of .frame
is increasing and .top
and .bottom
are showing with .fadeIn()
.
When the mouse is out .frame
, the size of .frame
is decreasing and .top
and .bottom
are going away with .fadeOut()
.
My CSS are:
.frame{
border-style: solid;
border-width: 1px;
width:200px;
height:200px;
position: absolute;
top:50px;
left:50px;
}
.middle{
width:100%;
position: absolute;
}
.top{
display:none;
background-color:red;
width:100%;
}
.bottom{
position:absolute;
display:none;
bottom:0px;
background-color:red;
width:100%;
}
my HTML:
<div class="frame">
<div class="top">top</div>
<div class="middle">middle</div>
<div class="bottom">bottom<br>bottom<br>bottom<br>bottom</div>
</div>
and my jQuery:
$(document).on('mouseenter mouseleave', '.frame', function( e ) {
var el = $(this),
top = el.children('.top'),
bottom = el.children('.bottom'),
middle = el.children('.middle'),
d = bottom.height()+20,
mEnt = e.type == "mouseenter";
if(mEnt == true){
middle.stop().animate({'top':'20px'});
el.stop().animate({
'height':'+='+d,
'top':'-=20'
});
top.stop().fadeIn(300);
bottom.stop().fadeIn(300);
}else{
middle.stop().animate({'top':'0px'});
el.stop().animate({
'height':'-='+d,
'top':'+=20'
});
top.stop().fadeOut(300);
bottom.stop().fadeOut(300);
}
});
here a jsFiddle: http://jsfiddle.net/malamine_kebe/Y6cbQ/
It's working well, but when the mouse is entering and leaving fast it's messing the whole thing. I put a .stop()
before all .animate()
but it doesn't seem to help.
Instead of .stop()
use .stop(true, true)
. This makes it so the queue of animations is cleared and the current animation finishes immediately (http://api.jquery.com/stop/).
You can see in the fiddle: http://jsfiddle.net/3gYtK/
$(document).on('mouseenter mouseleave', '.frame', function( e ) {
var el = $(this),
top = el.children('.top'),
bottom = el.children('.bottom'),
middle = el.children('.middle'),
d = bottom.height()+20,
mEnt = e.type == "mouseenter";
if(mEnt == true){
middle.stop().animate({'top':'20px'});
el.stop(true, true).animate({
'height':'+='+d,
'top':'-=20'
});
top.stop(true, true).fadeIn(300);
bottom.stop(true, true).fadeIn(300);
}else{
middle.stop().animate({'top':'0px'});
el.stop(true, true).animate({
'height':'-='+d,
'top':'+=20'
});
top.stop(true, true).fadeOut(300);
bottom.stop(true, true).fadeOut(300);
}
});