I want to trim the number of characters allowed using javascript. It works on load, but on resize the number goes to 0. Why is that? Can it be done without plugins?
Notes:
text-overflow
property is of no help here because I need more lines.
Not that css hack with the background image (Text overflow ellipsis on two lines)
No jquery plugins.
Thanks!
function trimWords(){//change number of words depending on width in the category blog page
var theString = $(".trimmed-words").html(); //the string
var contentWidth = $(document).width(); //get width of browser
if(contentWidth < 600){
var maxLength = 80 // maximum number of characters to extract
}
else if (contentWidth >= 600 && contentWidth < 1025){
var maxLength = 400
}
else if (contentWidth >= 1025 && contentWidth < 1279){
var maxLength = 40
}
else if (contentWidth >= 1279){
var maxLength = 75
}
//trim the string to the maximum length
var trimmedString = theString.substr(0, maxLength);
//re-trim if we are in the middle of a word
trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")));
$(".trimmed-words").html(trimmedString);
}
trimWords();
$(window).resize(trimWords)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="trimmed-words">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>