KANAYO AUSTIN KANE KANAYO AUSTIN KANE - 6 months ago 14
jQuery Question

JQuery fadeOut when the mouse is not moved

I have this jQuery code that

fadeIn
and
fadeOut
a child div on it's parent div
hover
. I want the child div to fadeOut after five seconds if the mouse is still hovering on the parent div but the mouse is not moving. And if it starts moving again the child div shows up again. You can see an example of what I mean in this short 20sec video: Here is the my code so far:

$(document).ready(function(){
$("#parent_div").hover(function(){
$("#child_div").fadeIn(500);
},
function(){
$("#child_div").fadeOut(500);
});
});

Answer

You need to use mousemove event to do this work. When mouse is moving on element, use fadeIn() and set a timer using setTimeout(). In timer and after multipe seconds use fadeOut().

var timer;
$("#parent").mousemove(function(){
    clearInterval(timer);
    $("#child").fadeIn(500);
    timer = setTimeout(function(){
        $("#child").fadeOut(500);   
    }, 2000); 
});
#parent {
    width: 100px;
    height: 100px;
    border: 1px solid black;    
}

#child {
    width: 100%;
    height: 100%;
    background: green;
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
    <div id="child"></div>
</div>