jquery: disappear div with delay; then appear/disappear on hover

1.6k views Asked by At

I'm pretty new to jquery, and with what bits and pieces I've gathered, I've been trying to get a certain effect.

Effect: Say I have some #div. Once the page loads, I want it to disappear after some delay, say 5000ms. But then I want it to show again in case of mouseover and disappear again on mouseout.

So far: Like I said, I'm pretty new, so I may have made some silly error, or this problem may have a simple enough solution but I looked and didn't find one clear enough, so bear with me. I can get the two effects to work separately, not together.

To elaborate, using this code, I can hide the #div on page load and I'm thinking since the css just makes the div transparent rather than hide/display:none, I should be able to make it reappear with an opacity:1.
Also, the delay does not seem to be working. (I tried and it delays a fadeOut(), but I guess that means I won't be able to do much with that div again?)

$(document).ready( function() {
$("#div")
    .fadeOut()
    .delay(5000)
    .queue(function() {
        $(this).css("opacity","0").dequeue();
    })
});

And I can make an "appear on mouseover + disappear on mouseout" effect using this:

$(document).ready(function(){
  $("#div").hover(function(){
    $("#div").css("opacity","1");
    },function(){
    $("#div").css("opacity","0");
  });
});

The main reason I've used opacity, as I said before, is because hiding the div won't let me make it reappear (as I understand).

So how can I combine the two effects? Any help is greatly appreciated.
Thanks in advance.


Update: For anybody interested/who stumbles upon this page later: @kkemple 's code below works perfectly; however I modified it slightly to show a nice delay after mouseout rather than a quick vanishing act. (There may be a better way to do this; this is just how I got it to work.)

$(document).ready( function() {
    $("#div").hover(function(){
          $("#div").css("opacity","1");
            },function(){
        setTimeout(function(){
           $("#div").animate({'opacity': 0});
        },50);
    });

});
1

There are 1 answers

2
kkemple On BEST ANSWER
$(document).ready( function() {
    setTimeout(function () {
        $("#div")
            .animate({
                'opacity': 0
            }, 300); //you can set a speed just like fadeOut() or fadeIn()
    },5000);

    $("#div").hover(function(){
        $("#div").css("opacity","1");
    },function(){
        $("#div").css("opacity","0");
    });

});