Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete old divs if there are more than 20 | jQuery

I need some help with my jQuery script. I have a page that refreshes every 10 seconds and new divs from a feed are getting appended at.

My script counts the divs and removes the last div when there are more than 20 divs. This works fine if the feed just appends 1 div at a time. But the feed can also append multiply divs at the same time. When this happens the count can exceed the max of 20 divs. The problem with this is that my script just deletes 1 div and not all the divs that exceed the 20 count.

This is my code:

var $auto_refresh = setInterval(function () {
    var $articleCount = $('div').length; 

    if ($articleCount > 20) {
        $('div:last-child').remove();
    }

    $autoUpdate();
}, 10000); // refresh every 10000 milliseconds for new items

I need to remove all extra divs so there are always 20 divs. I hope someone can help me out with this.

like image 253
timG Avatar asked Feb 08 '12 15:02

timG


1 Answers

Use jQuery.slice to get everything past number 20, and bin them - dead easy :)

var $auto_refresh = setInterval(function () {
    $('div').slice(20).remove();
    $autoUpdate();
}, 10000); // refresh every 10000 milliseconds for new items

http://api.jquery.com/slice/

like image 84
Joe Avatar answered Sep 22 '22 18:09

Joe