JSFiddle - React, Tailwind, and code Playground
by greatCar
HTML
//textarea partial sample without Edge problem
<div id="content"></div>
<div id="calculated"></div>
<div id="rendered"></div>
<br />
<span id="sp" class="my_class">Hello World</span>
<textarea style="height: 80px" onpropertychange="myUpdate()" oninput="myUpdate()" id="ta" class="my_class">Hello World</textarea>
CSS
.my_class{
font: 20px Arial;
white-space: nowrap;
};
.textDimensionCalculation {
position: absolute;
visibility: hidden;
height: auto;
width: auto;
white-space: nowrap;
}
JavaScript
//textarea partial sample without Edge problem calculateWordDimensions = function(text, classes, escape) {
classes = classes || [];
//textarea partial sample without Edge problem
if (escape === undefined) {
escape = true;
}
// classes.push('textDimensionCalculation');
var div = document.createElement('div');
// div.setAttribute('class', classes.join(' '));
if (escape) {
$(div).text(text);
} else {
div.innerHTML = text;
}
document.body.appendChild(div);
var dimensions = {
width : jQuery(div).outerWidth(),
height : jQuery(div).outerHeight()
};
div.parentNode.removeChild(div);
return dimensions;
};
myUpdate = function (){
var dimensions = calculateWordDimensions(document.getElementById("ta").innerHTML,['my_class']);
$("#calculated").html('Calculated width ' + dimensions.width);
document.getElementById("rendered").innerHTML=document.getElementById("ta").scrollHeight;
//$("#rendered").html("element text width "+ document.getElementById("ta").width());
};
myUpdate();