William William - 6 months ago 38
Javascript Question

jQuery - Read More / Read Less. How to replace text?

HTML:

<a href="#" class="show_hide" data-content="toggle-text">Read More</a>


jQuery:

// Slide Up Slide Down
$('.show_hide').toggle(function(){
$(this).text().replace("Read More", "Read Less");
$('.' + $(this).attr('data-content')).slideDown();

},function(){
$(this).text().replace("Read Less", "Read More");
$('.' + $(this).attr('data-content')).slideUp();
});


I am trying to make one of those "Read More / Read Less" buttons to hide and show text.

How do I replace "Read More" with "Read Less" on click?

Your input is much appreciated!

Answer

You could also use :visible to check if content is visible and change text accordingly.

$(document).ready(function () {
    $(".content").hide();
    $(".show_hide").on("click", function () {
        var txt = $(".content").is(':visible') ? 'Read More' : 'Read Less';
        $(".show_hide").text(txt);
        $(this).next('.content').slideToggle(200);
    });
});

JSFiddle Demo

Comments