I just had something similar working today while I was looking for an answer, but there seems to be nothing special.
Although I use Array.reduce() you should be able to do this with Array.forEach() or any other iterative code that you like.
words.reduce(function(acc, value)
This is done by calculating whether the element will be full if we add another word to it before we actually represent it. The hacker thing here is to add another block element inside it with visibility: hidden .
element.innerHTML = '<div style="visibility: hidden; height: 100%; width=100%">' + textToBeAdded + '</div>';
Thus, the block element is still taking its parent dimensions, and the parent element can be checked for overflow.
A way to check for overflow is to compare the scroll height of an element with its height:
if (element.scrollHeight > element.offsetHeight)
If it overflows, we leave it as it is, create a new element and put the current value (word) in an iteration. Then we attach it to the same DOM tree as the previous element (as a parent child ... like a new brother π)
var newPageEl = document.createElement('div'); newPageEl.classList = 'page'; newPageEl.textContent = word; parentElement.appendChild(newPageEl);
Hope this makes sense.
var page = document.getElementsByClassName('page')[0]; if (page.scrollHeight > page.offsetHeight) {
Charis theo
source share