I'd probably use .slice().

Something like this should work:

  $(document).ready(function() {
    var $list = $('.main ul'),
        $items = $list.find('li'),
        $moreLink = $('<a href="#">more</a>');

    if ($items.length > 10) {
      $moreItems = $('<ul></ul>').append($items.slice(10)).hide();
      $list.after($moreLink).after($moreItems);
      $moreLink.click(function() {
        $(this).text($(this).text() == 'more' ? 'less' : 'more');
        $moreItems.slideToggle();
        return false;
      });
    }
  });


--Karl

____________
Karl Swedberg
www.englishrules.com
www.learningjquery.com




On Jun 19, 2009, at 4:54 PM, bombaru wrote:


There has got to be a better way to write this?  Basically, I'm
returning a bunch of list item and after the 10th one, setting the
rest to display:none and adding a <more> link.  Clicking on the <more>
link removes the display:none and adds a <less> link at the bottom.

I think jQuery 1.3.2 is having some trouble with the nth-child
approach.  Can someone point me in the right direction on how to
improve this?

Thanks.


$(document).ready(function() {
           $('.main ul').each(function() {
               $('li', this).each(function(i) {
                   if (i > 9) {
                       if (i == 10) {
                           $(this).parent().append('<li id=\"toggleon
\" class=\"toggle\"><a href=\"#\">more >></a></li><li id=\"toggleoff\"
class=\"toggle\" style=\"display:none\"><a href=\"#\"><< less</a></
li>');
                       }
                       $(this).hide();
                   }
               });
           });

           $('li.toggle').click(function() {
               $(this).parent().find('li:nth-child(10) ~ li').toggle
();
               $(this).find('#toggleon').toggle();
               $(this).find('#toggleoff').toggle();
               return false;
           });
       });

Reply via email to