user3787036
user3787036

Reputation: 191

I'm trying to show a div for 5 seconds before fade it out and remove it. How can I do that?

So.. I'm trying to call a function that shows a div and keep it visible for 5 seconds and then fades it out in a fast fadeOut (1 sec, for example).

The way I'm doing is not exactly what I expected... I did this:

function myFunc() {
     $( ".myDiv" ).show( "fast", function() {});
     $(".myDiv").fadeOut(5000, function() {
          $(this).remove();
     });    
}

But as result I get a div fade during 5 seconds.. And I want to show 5 seconds e fadeOut fast. Thanks for the help.

Upvotes: 1

Views: 1503

Answers (5)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

I don't know why you used remove() .. while fadeOut will display it to none

function myFunc() {
     $( ".myDiv" ).fadeIn(5000).delay(2000).fadeOut('fast');
}

Upvotes: 0

Rahul Desai
Rahul Desai

Reputation: 15501

Instead of show, use fadeIn instead. And, the fadeOut should be inside the callback of setTimeout which triggeres it after 5 sec.

$( ".myDiv" ).fadeIn("fast");

setTimeout(function(){ 
    $(".myDiv").fadeOut("fast", function() {
        $(this).remove();
    });
}, 5000);
.myDiv{
  width: 100px;
  height: 100px;
  border: 5px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myDiv"></div>

jsFiddle Demo

Read up:

Upvotes: 1

Alien
Alien

Reputation: 3678

using jQuery delay()

function myFunc() {
     $( ".myDiv" ).show( "fast").delay(5000).fadeOut('fast', function() {
          $(this).remove();
     });    
}

here is jsFiddle http://jsfiddle.net/qwdv0bsu/1/

Upvotes: 3

ggdx
ggdx

Reputation: 3064

Try like this...

setTimeout('myFunc',5000);

This will do 'myFunc()' after 5 secs.

Upvotes: 0

SLeptons
SLeptons

Reputation: 17

draw you div normally then set a timer like the following:

setInterval(
    function () { 
     $(".myDiv").fadeOut(100, function() {
       $(this).remove();
    }); }, 
    5000
); 

Upvotes: 0

Related Questions