Andy Dwyer
Andy Dwyer

Reputation: 716

jQuery show hidden li elements, but then hide visible li elements

The following jQuery code calls the ul element, finds the first three li list items within the element and hides the remaining li items. Then, it appends an li element which says "Show more..." and, when clicked, reveals the previously hidden list items.

(jsFiddle at bottom of question)

$('ul')
  .find('li:gt(2)')
  .hide()
  .end()
  .append(
    $('<li>Show more...</li>').click( function(){
      $(this).siblings(':hidden').fadeIn(500);
   })
);

Simple enough. Now, in addition to showing the hidden list items when the user clicks "Show more...", I need it to also hide the first three list items which are originally left visible. By illustration:


What the code currently generates:

 - List Item #1
 - List Item #2
 - List Item #3
 - Show more...

(click)

 - List Item #1
 - List Item #2
 - List Item #3
 - List Item #4
 - List Item #5
 - Show more...

What needs to occur:

 - List Item #1
 - List Item #2
 - List Item #3
 - Show more...

(click)

 - List Item #4
 - List Item #5
 - Show more...

For usability purposes, I would also be nice if when "Show more..." is clicked again, the first three list items become visible again and the remaining list elements are hidden.

jsFiddle: http://jsfiddle.net/g9L9R/

Upvotes: 0

Views: 1473

Answers (5)

bipen
bipen

Reputation: 36551

Use visible to hide the rest:

 $('ul')
  .find('li:gt(2)')
  .visible('hide');

see jsfiddle here.

Upvotes: 0

charlietfl
charlietfl

Reputation: 171698

Solution independent of list length, hides the more at end

var list = $('ul'),
    start = 0,
    items = list.find('li').slice(0, 3).show().end(),
    more = $('<li>Show more...</li>').click(function() {
        start = start + 3
        var newItems = items.slice(start, start + 3)
        items.filter(':visible').add(newItems).toggle(500);
        if (newItems.length < 3) {
            more.hide()
        }
    }).show()
    list.append(more);

DEMO: http://jsfiddle.net/5WgYK/1/

Upvotes: 1

Anujith
Anujith

Reputation: 9370

See this: http://jsfiddle.net/g9L9R/7/

$('ul')
.find('li:gt(2)')
.hide()
.end()
.append(
  $('<li>Show more...</li>').click( function(){
  $(this).siblings().toggle(500);
})
);​

You will get a nice toggle effect here...

Upvotes: 6

ATOzTOA
ATOzTOA

Reputation: 36000

Try this out:

$('ul')
  .find('li:gt(2)')
  .hide()
  .end()
  .append(
    $('<li>Show more...</li>').click( function(){
      $(this).siblings(':visible').fadeOut(500);
        $(this).siblings(':hidden').fadeIn(500);
   })
);

jsFiddle: http://jsfiddle.net/g9L9R/4/

Upvotes: 2

Talha Akbar
Talha Akbar

Reputation: 10040

$("li").each( function() {
if($(this).is(":visible")) {
$(this).hide();
}
else {
$(this).show();
}
});

and onclick of a button

$("button").click( function() {
$("li").each( function() {
if($(this).is(":visible")) {
$(this).hide();
}
else {
$(this).show();
}
});
});

Upvotes: 2

Related Questions