jQuery toggle and changing text
Asked Answered
H

2

5

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

Hautesavoie answered 28/3, 2013 at 10:9 Comment(1)
possible duplicate of jQuery - slideToggle() and Toggle TextPatentor
R
14

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.
});
Rentschler answered 28/3, 2013 at 10:12 Comment(1)
Please not that this might be problem in if you do localisationDeedeeann
G
0

There is a minor amendment in the code because the above code did not work for me. I have Read More text with space on the left-right side so the ternary operator fails to recognize it. I added $.(trim) to make it work.

$('.readmore').click(function(e){
e.preventDefault();
$('#message div').slideToggle();
$(this).text( $.trim($(this).text()) == 'Read More' ? "Show Less" : "Read More"); // using ternary operator.
});
Gibert answered 27/9, 2022 at 13:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.