May 20, 2010

Truncate lists with Jquery

Question by Globulopolis

How can I add a function for hide/show elements in the list?

For example we’ve several lists. When we click on “show” link, all list items are displayed, when we click on “hide” link, hide items in a list with an index greater than 3.

<div class="filter_item">
...
<h3>Network Name:</h3>
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>
...
</div>

and js code

<script type="text/javascript">
    //<![CDATA[
        jQuery(document).ready(function($){
            $('.filter_item ul').each(function(){
                $('li:gt(2)', this).hide();
                if ($(this, 'li').children().length > 3) {
                    $(this, ':last').append('<li><a href="javascript:void(0);" class="tr_more">More...</a></li>');
                }
            });
            $('.tr_more').toggle(function(){
                $(this).closest('li').siblings().show();
                $(this).attr('class', 'tr_less').text("Less...");
            }, function(){
                ????
            });
        });
    //]]>
</script>

How to implement hide items when we click on “hide” link?

Answer by Kobi

While this seems overly complex, this will work for you:

$(this).closest('ul').children('li:gt(2):not(:last)').hide();

First it searches for the parent <ul>, and then hides child <li>s, but leaves the parent of the “Show/Hide” link.

Going with $(this).closest('li').prevAll().slice(2).hide(); didn’t work quite well – it hid the first nodes, not the last. prevAll seem to return elements in reverse order.

Answer by Starx

$('.hidelink').click(function(){
     $(this).children('li').hide();
});

This will do

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!