Last active
August 29, 2015 14:16
-
-
Save zachfedor/619b0393f03a18fc3a9e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/************************************** | |
*// Dynamic Word Wrapping | |
**************************************/ | |
function wrapWords() { | |
var element = document.getElementById('element-id'); // grab entry-title element | |
if (element != null) { // make sure it is on this page | |
var string = element.innerHTML; // grab its contents | |
string = string.replace(/<(?:.|\n)*?>/gm, ''); // strip it of any html elements (i.e. a <br> from previous run through) | |
var array = string.split(" "); // break the string into an array of words | |
element.innerHTML = ""; // delete the element's contents | |
var reversed = array.reverse(); // reverse the word order | |
var height = 0; // var for element height (which is 0 right now) | |
for (var i = 0; i < reversed.length; i++) { // for each word | |
reversed[i] += " "; // add a space at the end of it | |
element.innerHTML += reversed[i]; // append it to the elements contents | |
if (height != element.clientHeight) { // if the height has changed | |
reversed.splice(i, 0, "<br>"); // append a line break | |
i++; | |
} | |
height = element.clientHeight; // set new height | |
} | |
array = reversed.reverse(); // reverse the reversed order | |
string = array.join(""); // join the array without a delimiter | |
element.innerHTML = string; // replace the new contents, in order and with appropriate line breaks | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment