Yash Mathur
Yash Mathur

Reputation: 69

How do I make a div appear after a couple of seconds after mouseover with jQuery?

An image should also appear to show the loading process. In mouseout, the div should disappear. My code:

$("a").mouseenter(function() {
    var link = $(this).attr("href");
    $("#flash").show();
    $("#flash").fadeIn(3000).html("<img src='load.gif' />");
    $("#div"+link).slideDown(100);
    $("#flash").fadeOut();
});

$("a").mouseout(function() {
    $("#flash").fadeOut(1000);
}); 

Upvotes: 1

Views: 372

Answers (3)

Adam
Adam

Reputation: 9449

$("my-element").mouseenter(function(){
$(this).delay(2000).fadeIn();
});

Upvotes: 1

Kon
Kon

Reputation: 27441

I assume you want the div+link part to slide down after a couple of seconds? setTimeout() is good for that.

$("a").mouseenter(function(){

        var link = $(this).attr("href");
        $("#flash").show();
        $("#flash").fadeIn(3000).html("<img src='load.gif' />");

        setTimeout(function() {
           $("#div"+link).slideDown(100);
        }, 2000);

        $("#flash").fadeOut();
});

UPDATE: The problem with setTimeout is you can't cancel it once it's queued up. Instead you can try setInterval, because it returns an id of the timer that you can call clearInterval on later.

var timerId = null;

$("a").mouseenter(function(){
    var link = $(this).attr("href");
    $("#flash").show();
    $("#flash").fadeIn(3000).html("<img src='load.gif' />");

    timerId  = setInterval((function() {
                   clearInterval(timerId);
                   $("#div"+link).slideDown(100);
               }, 2000);

    $("#flash").fadeOut();
});

$("a").mouseout(function(){

    clearInterval(timerId);
    $("#flash").fadeOut(1000);

});

It's important that you call clearInterval, so that the function call doesn't keep repeating.

Upvotes: 0

iWeb
iWeb

Reputation: 233

Have a look at the jQuery's .delay() method:

It's basically like setTimeout but allows chaining.

Upvotes: 2

Related Questions