Last active
September 5, 2022 21:41
-
-
Save brendan-c/2c3d534e75176fdfa10609a9efeca99a to your computer and use it in GitHub Desktop.
Wrap new lines
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
function wrapNewLines(targetSelector, wrapEl = 'span', wrapClass = 'new-line') { | |
const content = document.querySelectorAll(targetSelector) | |
content.forEach(section => { | |
let sectionWidth = section.getBoundingClientRect().width | |
let words = section.innerText.split(/( )/g) | |
section.innerHTML = '' | |
words.forEach(word => { | |
section.innerHTML += `<span>${word}</span>` | |
}) | |
let lines = [] | |
let line = [] | |
let lineWidth = 0 | |
let spans = section.querySelectorAll('span') | |
spans.forEach((span, i) => { | |
let spanWidth = span.getBoundingClientRect().width | |
if (lineWidth + spanWidth <= sectionWidth - 1) { | |
line.push(span) | |
lineWidth += spanWidth | |
} else { | |
lines.push(line) | |
line = [] | |
lineWidth = 0 | |
line.push(span) | |
lineWidth += spanWidth | |
} | |
}) | |
if (line.length) lines.push(line) | |
let newLines = lines | |
.map( | |
line => | |
`<${wrapEl} class=${wrapClass}>${line | |
.map(span => span.innerText) | |
.join('')}</${wrapEl}>` | |
) | |
.join('') | |
section.innerHTML = newLines | |
}) | |
} | |
// Examples: | |
// wrapNewLines('.wrap-me') | |
// <span class='new-line'> ... </span> | |
// wrapNewLines('.wrap', 'div', 'line') | |
// <div class='line'> ... </div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment