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!
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).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With