Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 606
William Avatar asked Aug 16 '14 15:08

William


People also ask

How to add Read more and Read Less button in jQuery?

length); var strtoadd = firstSet + "<span class='second-section'>" + secdHalf + "</span><span class='read-more' title='Click to Show More'>" + readMoreTxt + "</span><span class='read-less' title='Click to Show Less'>" + readLessTxt + "</span>"; $(this).

What is text () in jQuery?

jQuery text() Method The text() method sets or returns the text content of the selected elements. When this method is used to return content, it returns the text content of all matched elements (HTML markup will be removed). When this method is used to set content, it overwrites the content of ALL matched elements.

How do I create a Read more in jQuery?

Answer: Use the JavaScript substring() method You can use the JavaScript substring() method in combination with the jQuery append() and html() methods to truncate the paragraphs of a text and add read more link at the end, if the number of characters inside a paragraph exceeds a certain length.


1 Answers

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

like image 64
imbondbaby Avatar answered Oct 08 '22 14:10

imbondbaby