Using jQuery to limit the number of list elements

jquery, limit, list

Solution

Well, fortunately for us programmers, who write code for food and fame, not every imaginable piece of functionality has been written yet as a plugin :)

But this is quite easy:

var from = 0, step = 5;

function showNext(list) {
  list
    .find('li').hide().end()
    .find('li:lt(' + (from + step) + '):not(li:lt(' + from + '))')
      .show();
  from += step;
}

function showPrevious(list) {
  from -= step;
  list
    .find('li').hide().end()
    .find('li:lt(' + from + '):not(li:lt(' + (from - step) + '))')
      .show();
}

// show initial set
showNext($('ul'));

// clicking on the 'more' link:
$('#more').click(function(e) {
  e.preventDefault();
  showNext($('ul'));
});

Of course this is better extracted into plugin-like function, but I'm gonna leave that as an exercise for a reader ;)

Problem

I have a list element containing a number of between 20-30 events. I only want to show 5 of those, and have a «More» link I can click to watch the the next five. It doesn't matter if the five next events are appended. Can't find a jQuery script that actually does this, or am I just blind? I don't want to use carousel plugins or anything like that.

Original source