How do I go about dynamically splitting a body of text into two even columns with plain Javascript (no JQuery)?
Tags: javascript,html,css
Problem :
I have already tried two approaches that don't seem to work: 1) I measured the total number of words and divided that by 2, but problems arise when there are really long words, and not all words are the same length, etc. 2) I measured the height in pixels of each character, the clientHeight of entire body of text, and divided the total height of the text by the height of one character to see how many lines go in one column and how many go in the other. This approach works really well except when an images, paragraphs, and other HTML tags need to be factored in.
I need to come up with a new approach that take images and other HTML tags into account, and I can only use HTML, CSS, and JavaScript (no JQuery, JSON, Ajax, etc). Let me know if you have an idea/algorithm! Thanks :)
Solution :
I created a quick and dirty "hack" for you on JSFiddle http://jsfiddle.net/uWUBE/
Hope it helps you out, you could edit it to be more dynamic. Here is some of the code. It basically loops trough the amount of words and then adds it to a string you assign to a column, I am not a Javascript mastermind at all so.. there might be a better way.
`
// Get the text
var txt = $("p").text();
// Split every word
var words = txt.split(" ");
// Count the amount of words
var amount = words.length
// Amount of columns
var columnAmount = 2
// Amount of words in first colum
var firstColumn = Math.floor(amount / columnAmount);
// String for first column
var firstColumnTxt = "";
// String for second column
var secondColumnTxt = "";
// loop trough the words and add them to the first column
for (var i = 0; i < firstColumn; i++){
firstColumnTxt = firstColumnTxt + " " + words[i];
}
// loop trough the words and add them to the second column
for (var i = firstColumn; i < amount; i++){
secondColumnTxt = secondColumnTxt + " " + words[i];
}
// Add this to your first column
console.log(firstColumnTxt);
// Add this to your second column
console.log(secondColumnTxt);
`