In addition to @SmokeyPhp answer:
First of all, that was a great answer that helped me a lot, but there were some mistakes in the condition there.
Second of all, I'm working with jqlite library instead of jQuery, so that answer was also very helpful in that area (all the methods he used were part of the jqlite library).
In addition to detecting the last visible word in a span or a div, my function is also replacing the rest of the text with "...".
I'm posting the code I'm using, basically the code @SmokeyPhp posted, but fixed where needed, 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/ids to dotdotdot, or a single class/id.
The $jq is the jqlite replacement for jQuery's $.
Thanks @SmokeyPhp, I looked for a long time for a method that does not require jQuery to dotdotdot text, and your method is fantastic.