Reputation: 13
I want to hide a Div after some time, if the mouse is not over it. this script is working, but I wonder how it could work better.
var i = null;
i = setTimeout(function () {
$("#info").hide("slow");
}, 7000);
$("#info").mousemove(function() {
clearTimeout(i);
}).mouseleave(function() {
i = setTimeout(function () {
$("#info").hide("slow");
}, 2000);
});
Upvotes: 0
Views: 71
Reputation: 1032
Edit: this is not exactly what the qeustion is about - just ignore this answer.
You can achieve this without javascript, with pure css:
yourDivClass {
opacity: 0;
-webkit-transition-delay: 2s; /* Safari */
transition-delay: 2s;
}
yourDivClass:hover {
opacity: 1;
transition: 0s ease all;
}
Upvotes: 1
Reputation: 2368
Your solution is right. One thing is check if i
is not null
before clearing the timeout. And if you want more pretty code, define the timeout callback as the separate function as follows:
var i = null;
i = setTimeout(hideInfo, 7000);
$("#info")
.mousemove(function() {
if(i){
clearTimeout(i);
}
})
.mouseleave(function() {
i = setTimeout(hideInfo, 2000);
});
function hideInfo(){
$("#info").hide("slow");
}
Upvotes: 1