How to show div for 10 seconds and then hide it
I have div block which comes on a mouseover of another div.
div1 img // mouse over shows div2.
I want to开发者_JAVA技巧 show div2 for 10 seconds and then hide it , can you please tell me how to achive this
Thanks
$("#div1").mouseenter(function() {
var $div2 = $("#div2");
if ($div2.is(":visible")) { return; }
$div2.show();
setTimeout(function() {
$div2.hide();
}, 10000);
});
Another way to go:
$("#div1").mouseenter(function() {
var $div2 = $("#div2");
if ($div2.data("active")) { return; }
$div2.show().data("active", true);
setTimeout(function() {
$div2.hide().data("active", false);
}, 10000);
});
Use jQuery's delay(n); method http://api.jquery.com/delay/
$(function() {
$("#div1 img").hover(function(){
$("#div2").show().delay( 10000 ).hide(0);
});
});
The accepted answer is the only good one here.
I'm leaving an answer because most of the others fail for various reasons.
If you want to use .delay()
, the item delayed needs to be part of the queue. The .hide()
method is not. But if you give .hide()
a duration, it is.
So you can do this:
var $div2 = $('#div2');
$('#div1').mouseenter(function() {
$div2.show().delay( 10000 ).hide( 0 );
});
The 0
duration makes .hide()
part of the queue. You don't want to use .hover()
because it will fire once for mouseenter
and once for mouseleave
. This is not what was wanted.
Some of the answers using setTimeout()
fail because if there are several mouseenter
events, then several setTimeout()
calls are made. The accepted answer gets around this.
as part of the mouseover function:
setTimeout(function(d){
item.hide();
}, 10000);
This assumes var item
is the jquery object of the div you want to hide. The parameter 10000
is the delay in milliseconds. 10s * 1000ms/1s = 10000ms
$(function() {
$("div1 img").hover(
function() { //mouse over show div
$("div2").show(); //.delay(10000).fadeOut();
},
function() { // mouse out, start timer to hide
//$("div2").delay(10000).fadeOut();
}
);
});
var $div2 = $('#div2');
$('#div1').mouseover( function(){
$div2.show();
setTimeout( function(){
$div2.hide();
}, 1000*10);
});
精彩评论