Quick and Easy jQuery Read More Script Tutorial

Written by Kevin Liew on 28 Oct 2010
105,502 Views • Tutorials

Introduction

Alright, back to jQuery tutorial after a long break. This time will be pretty simple script that hide the extra length of a long paragraph and toggle hide and show the extra sentence. I created it few days ago for the comment moderation in the backend, normally what I do is list out all the comment (with pagination of course) and display the first 20 words of the comment (following by 3 dots :)), and also a set of control such as view, approve and delete buttons. However, I found it annoying because if the comment is too long, you can't really read the comment from the list, because of that I will have to click on the view button to view it in another page. That's waste of time and bandwidth if you have a lot of comments to approve!

So I decided to make it easier, and that's when this script came into my mind. It able to hide the long comment and view it if the user wants to, then publish it. Simple and can be extremely useful! So, here we go, start with the first section - HTML

1. HTML

HTML is pretty basic, don't freak out because of the length of the following html, what we really need to pay attention is the P Tag with excerpt class. That is the description and will be reformatted by jQuery script.

<div class="row">
	<div class="img">
		<a href="http://www.link.com"><img data-src="images.gif" alt="" /></a>
	</div>
	<div class="desc">
		<h2><a href="http://www.link.com/">Lorem Ipsum der a lor</a></h2>
		<p class="excerpt">Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed molestie augue sit amet leo consequat posuere. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Proin vel ante a orci tempus eleifend ut et magna. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus luctus urna sed urna.</p>
	</div>
	<div class="clear"></div>
</div>

2. CSS

CSS is not important as well :). The following is the basic styling I used in the demostration. We do not have to worry about CSS for this tutorial!

	/* normal formating */
#table {
	margin:0 auto; 
	width:680px; 
	font-family:arial; 
	font-size:12px; 
	color:#333;
}

	#table .row {
		margin:15px 0 5px 0; 
		border-bottom:1px dotted #c4c4c4;
	}

	#table .img {
		width:160px; 
		height:100px; 
		float:left;
	}

	#table .img img {
		width:160px; 
		height:100px; 
		border:2px solid #333;
	}

	#table .desc {
		width:500px; 
		height:120px; 
		float:right;
	}
	
	#table .desc a {
		color:#2a8cba; 
		text-decoration:none;
	}
		
	#table .desc span {
		width:50px;
	}

	#table h2 {
		font-size:20px; 
		margin:0 0 5px 0; 
		padding:0;
	}
#table h2 a {text-decoration:none;}
.clear {clear:both}

3. Javascript

Alright, this is the core of the tutorial. What it does:

  1. Loop through the HTML tags that have a class called excerpt
  2. Then, grab the sentence in the element and reformat it so the length is checked and added necessary HTML elements.
  3. Lastly, in the click event, toggle hide and show of the extra content.

It's pretty straight forward, I have added inline comment for each of the section in the jQuery script for better understanding of what it really does. One thing though, I should have use the is(':visible') instead of hasClass('hide'), but apparently, IE8 is having problem to execute it, I don't really know what's wrong because i tried it in Firefox and Chrome, they both work perfectly fine. Just one of a random faulty behaviors from Microsoft Internet Explorer I guess.

$(function () {

	// Grab all the excerpt class
	$('.excerpt').each(function () {
	
		// Run formatWord function and specify the length of words display to viewer
		$(this).html(formatWords($(this).html(), 30));
		
		// Hide the extra words
		$(this).children('span').hide();
	
	// Apply click event to read more link
	}).click(function () {

		// Grab the hidden span and anchor
		var more_text = $(this).children('span.more_text');
		var more_link = $(this).children('a.more_link');
			
		// Toggle visibility using hasClass
		// I know you can use is(':visible') but it doesn't work in IE8 somehow...
		if (more_text.hasClass('hide')) {
			more_text.show();
			more_link.html(' &raquo; hide');		
			more_text.removeClass('hide');
		} else {
			more_text.hide();
			more_link.html(' &laquo; more');			
			more_text.addClass('hide');
		}

		return false;
	
	});
});

// Accept a paragraph and return a formatted paragraph with additional html tags
function formatWords(sentence, show) {

	// split all the words and store it in an array
	var words = sentence.split(' ');
	var new_sentence = '';

	// loop through each word
	for (i = 0; i < words.length; i++) {

		// process words that will visible to viewer
		if (i <= show) {
			new_sentence += words[i] + ' ';
			
		// process the rest of the words
		} else {
	
			// add a span at start
			if (i == (show + 1)) new_sentence += '... <span class="more_text hide">';		

			new_sentence += words[i] + ' ';
		
			// close the span tag and add read more link in the very end
			if (words[i+1] == null) new_sentence += '</span><a href="#" class="more_link"> &raquo; more</a>';
		} 		
	} 

	return new_sentence;

}	

Conclusion

That's about it, it's simple and can be really useful to solve the space problem in the design. I hope you enjoyed it and feel free to browse around for more tutorials and design inspirations.

Demo Download
Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

17 comments
jquery 13 years ago
Thanks for this simple tutorial, i do agree with you it will be quite useful!
Reply
kevin Admin 13 years ago
Thanks!
Reply
Stephan 13 years ago
Hello,

Nice script. I tested it and ran into a problem. How do you handle the <UL> and <OL>?
Reply
Kevin Liew Admin 13 years ago
Do you mean the text contains html tags? You will need to strip them off.
Reply
Rose Williams 13 years ago
Thankyou !

very useful.!
Reply
Don V 12 years ago
does anyone know if google spiders still count the words for that page if they are used under this script? Used say on a body text that you are wanting to shorten up but keep the word count?
Reply
Kevin Liew Admin 12 years ago
It should be, because Google spider can't execute Javascript, therefore, the document will loaded with full text.
Reply
Mary 12 years ago
This has been great! One favor/question... How or what would be the code to insert that would keep the vertical consistent? Say I have 7 topics with text, and when I show 1, the rest hide... and then when I click on topic 3, only it shows and the rest hide? I'm trying to prevent the vertical scrolling from activating if at all possible... Thanks for this!
Reply
Howida 11 years ago
what if i want it flexible paragraph, meaning some paragraphs i need to show more than lines. in your function you limit the length of words to 30, i just want to make it variable so i can enter this value according to what i need. sorry am new to java scripting.
Reply
JohnMc 11 years ago
Hey, just wanted to say thanks for the script, very useful and easy to use!
Reply
Chris Spaulding 11 years ago
Awesome script but not working in IE8 or IE7 for me. Can anyone confirm?
Reply
Mario 11 years ago
Thanks, this is great. would it be possible (and how) to remove the ellipsis when clicking on <more> and pitting it back when clicking on <hide>?
Reply
Kevin Liew Admin 11 years ago
You can remove it from javascript line 54.
Reply
Tim G 11 years ago
Thank you soooo much for this!!!!! I have tried maybe a half dozen different methods for a read more button but all have failed. They have been hard to use with data that is retrieved from a database and displayed in a grid view but this works PERFECTLY!!! Thank you again :)
Reply
JC 11 years ago
I'm using this script, and I have a link after the "Read More" tag. Whenever I try to click the link, it just hides the text. Is there any way I can fix this?
Reply
Jüri 11 years ago
Hi, great script, thanks a lot!!! I spent huge amount of time looking for this simple solution! Got it working in no time! The question about <li> elements still important for me... I have a veeeery long list that I would really like to shorten with this script in default view. You said html should be stripped? That would destroy the whole layout unfortunately.... any ideas?
Reply