23

I have written a jquery script that allows me to fade divs in and out, then repeat. The code works fine. However, when I try to add a delay (I want the div to stay up a few seconds before fading out), it does not work properly. I've tried adding the delay in several places inside the code and none seem to function properly. I am using Jquery version 1.9.1

Here is the script that I have written:

$(document).ready(function(){
   ShowPostDiv(0);
});

function ShowPostDiv(divIndex)
{
    $(".home_entry_txt").hide();

    if(divIndex >= $(".rotate_hide").length)
    {
        divIndex = 0;
    }
    var divPostHtml = $(".rotate_hide:eq("+divIndex+")").html();
    $(".home_entry_txt").html(divPostHtml); 
    $(".home_entry_txt").fadeIn(3000, function(){
             $(".home_entry_txt").fadeOut("slow");
        });
    divIndex++;
    setTimeout("ShowPostDiv("+divIndex+")", 4000);
}
user2220474
  • 293
  • 1
  • 4
  • 15
  • Have you tried $(".home_entry_txt").delay(5000).fadeOut("slow"); ? – isotrope Mar 28 '13 at 16:05
  • As a side note, you should use an anonymous function with setTimeout, rather than a string. So, `setTimeout(function() { ShowPostDiv(divIndex); }, 4000);` – Colin DeClue Mar 28 '13 at 16:12

3 Answers3

43

You can just write

$(".home_entry_txt").fadeIn(3000).delay(1000).fadeOut("slow");
enb081
  • 3,831
  • 11
  • 43
  • 66
5

Have you tried .delay()? something like:

$(".home_entry_txt").fadeIn().delay(200).queue(function(next) {
$(".home_entry_txt").fadeOut("slow");
});
kelly johnson
  • 1,596
  • 3
  • 16
  • 26
3

try this

$(document).ready(function(){
   ShowPostDiv(0);
});

function ShowPostDiv(divIndex)
{
    $(".home_entry_txt").hide();

    if(divIndex >= $(".rotate_hide").length)
    {
        divIndex = 0;
    }
    var divPostHtml = $(".rotate_hide:eq("+divIndex+")").html();
    $(".home_entry_txt").html(divPostHtml); 
    $(".home_entry_txt").fadeIn(3000, function(){
        setTimeout(function(){
            $(".home_entry_txt").fadeOut("slow");
        },4000);
    });
    divIndex++;
}
iAmClownShoe
  • 606
  • 1
  • 4
  • 10
  • Thanks! Trying this caused it to fade in, stay a while, then fade out. This is what I want. However, it does not repeat with the next div. How would I get it to repeat again for the next div to fade in, stay a while, then fade out? – user2220474 Mar 28 '13 at 19:21
  • im not sure what you mean by the next div? – iAmClownShoe Mar 28 '13 at 19:46