Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery change append onClick

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?

like image 411
Andy Dwyer Avatar asked Dec 04 '22 00:12

Andy Dwyer


2 Answers

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

like image 71
WooCaSh Avatar answered Dec 05 '22 15:12

WooCaSh


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);
        })
    );​
like image 45
Shmiddty Avatar answered Dec 05 '22 15:12

Shmiddty