4

I have the following jQuery code which locates the ul element on the page, hides any li items after the third item within that ul element and appends a "Show More!" text link which reveals/toggles the hidden list items when clicked.

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

An example of the script's functionality: http://jsfiddle.net/vf6j5/

Here's what I'd like the script to do: When the hidden elements are revealed after "Show More!" is clicked, I'd like the "Show More!" text to be replaced with "Show Less!". Doing this would be much more user friendly and make a bit more sense.

Any ideas on how this could be accomplished?

Andy Dwyer
  • 696
  • 1
  • 10
  • 30
  • possible duplicate of [Button text toggle in jquery](http://stackoverflow.com/questions/13652835/button-text-toggle-in-jquery) – epascarello Dec 28 '12 at 18:30

6 Answers6

5

http://jsfiddle.net/vf6j5/2/

$('ul')
    .find('li:gt(2)')
    .hide()
    .end()
    .append(
        $('<li>Show More!</li>').click(function() {
            var txt = $(this).text() == "Show More!" ? "Show Less!" : "Show More!";
            $(this).text(txt).siblings(':gt(2)').toggle(500);
        })
    );​
Shmiddty
  • 13,847
  • 1
  • 35
  • 52
5

Look on this:

$('ul')
        .find('li:gt(2)')
         .hide()
        .end()
        .append(
            $('<li class="title">Show More!</li>').click( function(){
            $(this).siblings().toggle(500);
                $(".title").html() === "Show More!"
                    ? $(".title").html("Show Less!")
                    : $(".title").html("Show More!")

            })
        );

Worked code

WooCaSh
  • 5,180
  • 5
  • 36
  • 54
4
$('ul').find('li:gt(2)').hide().end().append(
$('<li>Show More!</li>').click(function() {
    var $this = $(this);
    $this.siblings().toggle(500);
    $this.text(function(i, t) {
        return t === 'Show More!' ? 'Show Less!' : 'Show More!'
    })
}));

http://jsfiddle.net/aGeMp/

Ram
  • 143,282
  • 16
  • 168
  • 197
3
$('ul').find('li:gt(2)')
       .hide()
       .end()
       .append(
         $('<li>Show More!</li>').click(function() {
            $(this).text($(this).prev('li').is(':visible') ? 'Show More' : 'Show Less')
                   .siblings().toggle(500);
         })
       );​

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

Pretty simple - select the element you want to change and modify its text

$('#myButton').text('Show Less!');
Charles Wyke-Smith
  • 2,479
  • 3
  • 17
  • 16
0

Since you already have this in the click event, just call .text() on it:

.... .click(function() {
  var that = $(this);
  that.siblings().toggle(500);
  that.text("Show less!");
});
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592