In addition to @SmokeyPhp, the answer is:
First of all, it was a great answer, which helped me a lot, but there were some mistakes.
Secondly, I work with the jqlite library instead of jQuery, so the answer was also very useful in this area (all the methods that he used were part of the jqlite library).
Besides detecting the last visible word in a range or div, my function also replaces the rest of the text with "...".
I am posting the code I'm using, basically the @SmokeyPhp code is posted, but fixed where necessary, and I hope others will benefit from it:
function dotdotdot(containersToDotdotdot) { function dotdotdotContainers(containers) { for (var i = 0; i < containers.length; i++) { var cntnr = $jq(containers[i]); cntnr.html('<span>' + cntnr.html().replace(/ /g,'</span> <span>') + '</span>'); var words = Array.prototype.slice.call(cntnr.find("span"), 0).reverse(); var lastw = null; for (var j = 0; j < words.length; j++) { var w = $jq(words[j]); var wbot = w.height() + w.offset().top; var wleft = w.offset().left; var wright = wleft + w.width(); if (wbot <= (cntnr.offset().top + cntnr.height()) && wleft >= (cntnr.offset().left) && wright <= (cntnr.offset().left + cntnr.width())) { lastw = words.length - j - 1; break; } } cntnr.html(lastw === null || lastw === (words.length - 1) ? cntnr.text() : (cntnr.text().split(' ').slice(0, lastw).join(' ') + '...')); } } if (containersToDotdotdot instanceof Array) { for (var i = 0; i < containersToDotdotdot.length; i++) { dotdotdotContainers($jq(containersToDotdotdot[i])); } } else { dotdotdotContainers($jq(containersToDotdotdot)); } }
As you can see, my dotdotdot function can get an array of classes / identifiers for dotdotdot or a single class / id.
$ jq - jqlite replacement for jQuery $.
Thanks @SmokeyPhp, I have been looking for a method for a long time that does not require jQuery for dotdotdot text, and your method is fantastic.
source share