I'm trying to truncate the amount of text in a div when the text reaches 40 characters in length and add an ellipsis after the truncation. This is my code:
jQuery(document).ready(function($) {
$(".trim").text(function(index, text) {
return text.substr(0, 40)+' ...';
});
});
The problem is it adds the ellipsis even if the character length is less than 40 characters, adding an ellipsis even when the text is no truncated. So next I tried a conditional to run the function only if the character length is less than 40 characters, to no avail:
jQuery(document).ready(function($) {
if($(".trim").length > 40) {
$(".trim").text(function(index, text) {
return text.substr(0, 40)+' ...';
});
}
});
Any ideas?
You're almost there! Your condition is not checking against the length of the text in the div. You are checking the .length
of the jQuery object, which would be equal to 1
(number of elements found by the selector). You need to check against the length of the actual text inside the div
. Get rid of the if
outside and move the length-check inside the function that you pass into .text()
:
$(".trim").text(function(index, text) {
var newText = text;
if(text.length > 40) {
newText = text.substr(0, 40) + "...";
}
return newText;
});