Quick and Easy jQuery Read More Script Tutorial

Quick and Easy jQuery Read More Script Tutorial


Quick and Easy jQuery Read More Script Tutorial

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 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.

Author: Kevin Liew

Kevin Liew is a web designer and developer and keen on contributing to the web development industry. He loves frontend development and absolutely amazed by jQuery. Feel free to say hi to me, or follow @quenesswebblog on twitter.

Share the love

16 comments

jquery
Tue, 2nd November 2010
Thanks for this simple tutorial, i do agree with you it will be quite useful! Reply
kevin Admin
Tue, 2nd November 2010
Thanks! Reply
Stephan
Tue, 6th September 2011
Hello,

Nice script. I tested it and ran into a problem. How do you handle the <UL> and <OL>? Reply
Kevin Liew Admin
Wed, 14th September 2011
Do you mean the text contains html tags? You will need to strip them off. Reply
Rose Williams
Sun, 18th September 2011
Thankyou !

very useful.! Reply
Don V
Tue, 20th December 2011
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
Tue, 20th December 2011
It should be, because Google spider can't execute Javascript, therefore, the document will loaded with full text. Reply
Mary
Fri, 6th January 2012
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
Wed, 7th November 2012
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
Thu, 22nd November 2012
Hey, just wanted to say thanks for the script, very useful and easy to use! Reply
Chris Spaulding
Sun, 30th December 2012
Awesome script but not working in IE8 or IE7 for me. Can anyone confirm? Reply
Mario
Tue, 5th March 2013
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
Tue, 26th March 2013
You can remove it from javascript line 54. Reply
Tim G
Thu, 9th May 2013
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
Thu, 19th September 2013
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
Sat, 28th September 2013
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

Leave a Comment

Please keep in mind that comments are moderated and rel="nofollow" is in use. You can use [code][/code] if you want to write codes. Don't spam us :) Thanks!

Advertisement