Today’s topic is jQuery Add More or Less Link into Paragraph. There are many plugins that are used to show more and less link on the paragraph.
We are showing more and less link on paragraphs using jquery core which saves you loading plugin time when you will use a plugin for this work.
This is a simple three steps coding to achieve this wonderful functionality. We are using jQuery to show/hide text and links.
You can also check other tutorials of dynamic read more Using Server side PHP and Mysql
We will create a paragraph in HTML in a div.
<div class="comment more">consectetur adipiscing elit. Proin blandit nunc sed sem dictum id feugiat quam blandit. Donec nec sem sed arcu interdum commodo ac ac diam. Donec consequat semper rutrum. Vestibulum et mauris elit. Vestibulum mauris lacus, ultricies.</div>
Now we will define the CSS class for a link.
a { color: #0254EB } a:visited { color: #0254EB } a.morelink { text-decoration:none; outline: none; } .morecontent span { display: none; } .comment { width: 400px; background-color: #f0f0f0; margin: 10px; }
jQuery code for more and less link on click event.
$(document).ready(function() { var showChar = 100; var ellipsestext = "…"; var moretext = "more"; var lesstext = "less"; $('.more').each(function() { var content = $(this).html(); if(content.length > showChar) { var c = content.substr(0, showChar); var h = content.substr(showChar-1, content.length – showChar); var html = c + '' + ellipsestext+ ' ' + h + ' ' + moretext + ''; $(this).html(html); } }); $(".morelink").click(function(){ if($(this).hasClass("less")) { $(this).removeClass("less"); $(this).html(moretext); } else { $(this).addClass("less"); $(this).html(lesstext); } $(this).parent().prev().toggle(); $(this).prev().toggle(); return false; }); });
I hope this helps you.
You can download the source code and see Demo from the below link.