Requirement:
- You have a list of dynamically generated p tags on your page and the length of the contents varies abnormally.
- You want to normalize the length of the content of the p tags to a threshold value of 350 characters.
- For all the p tags having length greater than 350, the remaining content should be hidden and there should be a link saying ‘… more’.
- There should be a tolerance limit of 20 characters i.e. if the p tags having length equal to 370 (350 + 20) characters, it should be left as it is.
Method body:
function SetMoreLess(para, thrLength, tolerance, moreText, lessText) {
var alltext = $(para).html().trim();
if (alltext.length + tolerance < thrLength) {
return;
}
else {
var firstHalf = alltext.substring(0, thrLength);
var secondHalf = alltext.substring(thrLength, alltext.length);
var firstHalfSpan = '' + firstHalf + '';
var secondHalfSpan = '' + secondHalf + '';
var moreTextA = '' + moreText + '';
var lessTextA = '' + lessText + '';
var newHtml = firstHalfSpan + moreTextA + secondHalfSpan + lessTextA;
$(para).html(newHtml);
}
}
Step 1: add class “summary” to the p tag(s)
Step 2: Iterate over all p tags and call the above function SetMoreLess like this.
SetMoreLess($(this).find("p.summary"), 350, 20, " ... more", " ... less");
Step 3: bind ShowMore and ShowLess click events ( in page_load or $(document).ready())
$("a.moreText").click(function () {
$(this).hide();
var pTag = $(this).parents("p.summary");
$(pTag).find("a.lessText").show();
$(pTag).find("span.secondHalf").show();
});
$("a.lessText").click(function () {
$(this).hide();
var pTag = $(this).parents("p.summary");
$(pTag).find("a.moreText").show();
$(pTag).find("span.secondHalf").hide();
});
Step 4: add css styles used in the code
a.moreText
{
color: blue;
cursor: pointer;
padding-left: 5px;
padding-right: 10px;
}
a.lessText
{
cursor: pointer;
color: blue;
display: none;
padding-left: 5px;
padding-right: 10px;
}
span.secondHalf
{
display: none;
}
Download example here.
1 comment:
HI
I found your example after much "googling" my issue. I'm basically trying to do exactly this except the text I want to control is coming from an .xml dataset named {Complete_description}.
All I want is for this feature to be available for the {Complete_Description}. Can you help me out?
Post a Comment