I am trying to add read more functionality to some text which includes heading and paragraphs. But it is showing all the text in one line. I want the text in formatting while clicking on read more.
Here is my code which I am using:
$(function() {
var minimized_elements = $('.case-desc');
minimized_elements.each(function() {
var t = $(this).text();
if (t.length < 200) return;
$(this).html(
t.slice(0, 200) + '<span>... </span><a href="" class="umore">More</a>' +
'<span style="display:none;">' + t.slice(200, t.length) + ' <a href="" class="uless">Less</a></span>'
);
});
$('a.umore', minimized_elements).click(function(event) {
event.preventDefault();
$(this).hide().prev().hide();
$(this).next().show();
});
$('a.uless', minimized_elements).click(function(event) {
event.preventDefault();
$(this).parent().hide().prev().show().prev().show();
});
});
Is it possible to get the text with formatting as I cannot remove heading and want to show as it is.
Here is how my text looks like
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
But I am getting
What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
var t = $(this).text();fetches just the text, so will effectively strip all the tags. See api.jquery.com/text "Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements." - Chris Lear.html()instead of.text()to preserve formatting. Then you cannot cut off at a fixed length of 80 with.slice(), you will have to parse the HTML in order to not cut off in the middle of an HTML tag or attribute. Another way is to loop through.children()instead. - Peter Krebs