Skip to content

Instantly share code, notes, and snippets.

@Hibrix-net
Last active August 1, 2020 14:21
Show Gist options
  • Save Hibrix-net/44df73e6d35d1388fa40f351db1a344e to your computer and use it in GitHub Desktop.
Save Hibrix-net/44df73e6d35d1388fa40f351db1a344e to your computer and use it in GitHub Desktop.
JS vanilla trim text with iteration loop
// Trim to 15 words
document.addEventListener("DOMContentLoaded", function() {
var myElements = document.getElementsByClassName('elemsToTrim');
// Real improved for loop: https://stackoverflow.com/questions/31352367/how-can-i-make-sublime-texts-improved-native-for-loop-increment-like-a-normal#answer-31352368
for (var i = 0, l = myElements.length; i < l; ++i) {
delay(i);
}
function delay(i) {
// Sometimes could be useful to make it async in order to avoid blocking the JS event loop
setTimeout(function() {
var myEl = myElements[i].innerText.split(" ").splice(0, 15).join(" ");
myElements[i].innerText = myEl.slice(-1) == '.' ? myEl : myEl + ' ...';
}, 0);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment