Reputation: 1055
I'm gonna add the animation for div tag such as fadein and fadeout.
When the user putting the mouse on the div tag, that one will be faded out.
When the user putting the mouse out of the div tag, that one will be faded in.
This is test code.
$('#div1').mouseleave(function(){
$('#div1').fadeIn();
console.log("out");
});
$('#div1').mouseover(function(){
$('#div1').fadeOut();
console.log("in");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">hover over me</div>
But when the user put the mouse on the div tag, the animation is repeated.
How could I fix this?
Upvotes: 1
Views: 1689
Reputation: 1193
Well, you don't have to use jQuery here! You could use plain CSS.
div {
background-color: red;
transition: 1s opacity ease; /* this here makes sure that all changes to the "opacity" element happen over 1 second. */
}
div:hover {
opacity: 0;
}
<div>
Aravind!
</div>
Upvotes: 0
Reputation: 22480
The problem is if you :hover
and fadeOut()
what happens is the element becomes display: none;
(you will see in my example the green box) so when it is fadeOut()
the element is not there anymore and so the mouseleave
gets called. To fix that issue is to hide a child element and keep the parent (orange box
) so the mouse is still over the parent #div1
...
$('#div1').mouseleave(function(){
$(this).children('.fade-me').fadeIn();
console.log("out");
});
$('#div1').mouseover(function(){
$(this).children('.fade-me').fadeOut();
console.log("in");
});
#div1 {
background-color: orange;
padding: 10px;
min-height: 20px;
}
#div1 > div {
background-color: green;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">
<div class="fade-me">hover over me</div>
</div>
You know that you can do this with CSS
only? Let me know if you need a CSS
only example.
Upvotes: 2