Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery toggle and changing text

jQuery

$('#message div').hide();
    $('.readmore').click(function(e){
        e.preventDefault();
        $('#message div').slideToggle();
    });

html

<div id="message">
    <p class="intro">This is an introduction.</p>
            <div>
            <p>This is the first paragraph thats orginally hidden</p>
        <p>This is the second paragraph</p>
            </div>
            <a href="#" class="readmore">Read More</a>
        </div><!--message-->

When the read more button is clicked the content is slideToggled and shows to everyone and clicked again it hides to only show my .intro but I would like to toggle the Read More text between Read More and Show Less.

How is this possible whilst using slideToggle

like image 324
ngplayground Avatar asked Mar 28 '13 10:03

ngplayground


1 Answers

Check the text of current element inside its click event and use condition, see if you have to change the text if yes, change it using text() again ;).

Try this:

 $('.readmore').click(function(e){
    e.preventDefault();
    $('#message div').slideToggle();
    $(this).text( $(this).text() == 'Read More' ? "Show Less" : "Read More"); // using ternary operator.
});
like image 76
bipen Avatar answered Oct 10 '22 23:10

bipen