Question

So, I made a example of a list propagation, and I totally spaced .append() for .after() so I was appending inside the master <li> which was very silly. However, what I thought was a one word fix... turned out to be very different. After changing .append() to .after() it will only populate once, and the interval doesn't continue.

var list = $('#theList li:last-child'),
    limit = 20,
    current = 0;

function rand() {
    return Math.random().toString(36).substr(2); // Just for some random contnt
}

$('#trigger').click(function() { // We're using a static button to start the population of the list
    var end = setInterval(function() {
        if ( current == limit ) {
            current = 0;
            clearInterval(end);
        }
        list.append('<li style="display:none;color:green;">' + rand() + '</li>');
        var newList = $('#theList li:last-child');
        newList.fadeIn();
        var colorEnd = setInterval(function() {
            newList.css('color', 'black');
            clearInterval(colorEnd);
        }, 350);
        current++;
    }, 300);
});

Fixed Code using Jack's Suggestions (DEMO)

var list = $('#theList li:last-child'),
    limit = 20,
    current = 0;

function rand() {
    return Math.random().toString(36).substr(2); // Just for some random contnt
}

$('#trigger').click(function() { // We're using a static button to start the population of the list
            var end = setInterval(function() {
            if ( current == limit ) {
                current = 0;
                clearInterval(end);
            }
            var elm = $('<li style="display:none;color:green;">' + rand() + '</li>');
            list = elm.insertAfter(list);               
            elm.fadeIn();
            var colorEnd = setInterval(function() {
                    elm.css('color', 'black');
                    clearInterval(colorEnd);
            }, 350);
            current =  current + 1;
        }, 300);
});

after() Version

append() Version

Was it helpful?

Solution

The problem is that list doesn't get updated; once the first .after() has taken place, it no longer is the last child; the elements are still added, but they remain invisible while you keep updating the already visible element from the first iteration.

You could update it like so:

var el = $('<li style="display:none;color:green;">' + rand() + '</li>')

list = el.insertAfter(list);

el.fadeIn();
// etc.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top