0

Got this script from an earlier post (here)

I edited this a bit so now i got:

<div id="outer" style="display: none"></div>

$(document).ready(function() {
$("#outer").css("display","block");
var $divs = $("#outer > div").hide(),
    current = 0;

$divs.eq(0).show();
function loadContent() {
    for(var i=0; i<20; i++) {
        $("#outer").append("<div id='divs"+i+"'>test"+i+"</div>");
    }  
}
function showNext() {
    if (current < $divs.length - 1) {
        $divs.eq(current).delay(2000).fadeOut('fast', function() {
            current++;
            $divs.eq(current).fadeIn('fast');
            showNext();
        });
    }
}
loadContent();
showNext();

});​

The jQuery that shows and hides the divs work if I just put some into the HTML. But not when I append them in my function.

Fiddle

Community
  • 1
  • 1

1 Answers1

1

You need to hide the divs after you have loaded them (by invoking loadContent), and invoke showNext once they are hidden:

$(document).ready(function() {
    $("#outer").css("display","block");
    var current = 0;

    function loadContent() {
        for(var i=0; i<20; i++) {
            $("#outer").append("<div id='divs"+i+"'>test"+i+"</div>");
        }  
    }

    function showNext() {
        if (current < $divs.length - 1) {
            $divs.eq(current).delay(2000).fadeOut('fast', function() {
                current++;
                $divs.eq(current).fadeIn('fast');
                showNext();
            });
        }
    }
    loadContent();
    var $divs = $("#outer > div");
    $divs.hide();
    showNext();
});

Here is a demonstration: http://jsfiddle.net/rZ2yF/1/

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
  • It works in the Fiddle... But when I paste it into my code I got: Unexpected token ILLEGAL at :59, which is, where the ready-handler ends `});´ – Daniel Nielsen Nov 29 '12 at 12:47
  • @DanielNielsen Yes, yes it does. – Asad Saeeduddin Nov 29 '12 at 12:48
  • You must be copying it incorrectly then. You have a couple of strange quote like things around the parentheses you included in your comment, those aren't present in my code. – Asad Saeeduddin Nov 29 '12 at 12:58
  • @DanielNielsen The only problem here is that you are using a function called `localAnswers` which you haven't defined. – Asad Saeeduddin Nov 29 '12 at 13:23
  • It's included from another script file (included in HTML before this script)... It's defined, yes? – Daniel Nielsen Nov 29 '12 at 13:39
  • sorry for the late comment, but there's a [problem with copying from fiddle](http://stackoverflow.com/questions/11551088/why-does-my-jsfiddle-work-but-not-my-web-site) (invisible characters show up in your code). Just remove the invisible code at line 59, after });. Click the link in my comment for more details. – hexicle Aug 12 '13 at 08:17