JSFiddle - React, Tailwind, and code Playground
by BurpmanJunior
HTML
<div id="target">
Example article title would end up here
</div>
CSS
@import url(https://fonts.googleapis.com/css?family=Playfair+Display:700);
#target{
font-family: 'Playfair Display', sans-serif;
font-size: 100px;
max-width: 900px;
}
#target span{
background-color: #000;
color: #fff;
}
JavaScript
console.clear();
var stackFromBottom = function(elem){
this.ELEM = elem;
this.processText();
this.addBreaks();
}
stackFromBottom.prototype.processText = function(){
var _this = this,
text;
text = _this.ELEM.textContent.trim().split(' ');
_this.ELEM.innerHTML = '';
text.forEach(function(word){
var span = document.createElement('span');
span.innerHTML = word + ' ';
_this.ELEM.appendChild(span);
});
}
stackFromBottom.prototype.addBreaks = function(){
var spans,
maxWidth;
this.clearBreaks();
maxWidth = this.ELEM.offsetWidth;
spans = this.ELEM.querySelectorAll('span');
console.log(maxWidth);
for(var i = spans.length - 1, x = 0; i >= 0; i--){
console.log(spans[i].offsetWidth);
if(x + spans[i].offsetWidth > maxWidth){
maxWidth = x;
spans[i].innerHTML = spans[i].innerHTML.trim();
var br = document.createElement('br');
spans[i].parentNode.insertBefore(br, spans[i].nextSibling);
x = spans[i].offsetWidth;
}else{
x = x + spans[i].offsetWidth;
}
}
console.log(this.ELEM.textContent);
}
stackFromBottom.prototype.clearBreaks = function(){
var breaks;
breaks = this.ELEM.querySelectorAll('br');
Array.prototype.forEach.call(breaks, function(br){
br.parentNode.removeChild(br);
});
}
new stackFromBottom(document.querySelector('#target'));