Measure Text Comprehensive
(was bfu6Lzex/16/)
by greatCar
HTML
<span>wrap</span>
<input id="cbWrap" type="checkbox" onclick="itemchecked()"/>
<div id="content"></div>
<div id="calculated"></div>
<div id="rendered5"></div>
<br>
<div id="rendered"></div>
<div id="rendered2"></div>
<div id="rendered3"></div>
<div id="rendered4"></div>
<div>
<span>Span text: </span><span id="mySpan" class="my_class">Hello World</span>
<br />
<br />
</div>
<br />
<br />
<textarea style="height: 80px; width:500px;" class="my_class" onChange="myUpdateXXXX()" oninput="myUpdate()" id="ta">My text area!</textarea>
CSS
.my_class{
font:12px Arial ;
white-space: ;
color: blue;
}
.textDimensionCalculation {
position: absolute;
visibility: hidden;
height: auto;
white-space: ;
}
JavaScript
$("#ta").css( "white-space", "nowrap" );
$("#mySpan").css( "white-space", "nowrap" );
calculateTextAreaEdgeOK = function(text, classes, escape) {
//shows span and div measurement from the original sample plus:
//also shows textarea properties: scrollHeight, etc.
classes = classes || [];
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).innerWidth(),
height : jQuery(div).outerHeight()
};
div.parentNode.removeChild(div);
return dimensions;
};
itemchecked=function(){
if (document.getElementById('cbWrap').checked){
$("#ta").css( "white-space", "wrap" );
$("#mySpan").css( "white-space", "wrap" );
$("#mySpan").css( "color", "green" );
//alert('CHECKED');
}
else{
$("#ta").css( "white-space", "nowrap" );
$("#mySpan").css( "white-space", "nowrap" );
$("#mySpan").css( "color", "brown" );
//alert('NOT CHECKED');
}
}
myUpdate = function (){
var myText = $( "#ta").val().trim();
$("#mySpan").text(myText);
//$("#ta").css( "white-space", "nowrap" );
//$("#mySpan").css( "white-space", "nowrap" );
var dimensions = calculateTextAreaEdgeOK(myText,['my_class']);
var spanWidth = $("#mySpan").width();
var calculatedDivWidth = dimensions.width;
$("#calculated").html('Calculated div width ' + calculatedDivWidth);
if(spanWidth !== calculatedDivWidth){
alert ("not equal; spanWidth: " + spanWidth + " divWidth: " + calculatedDivWidth);
};
document.getElementById("rendered").innerHTML='textarea scrollheight' +document.getElementById("ta").scrollHeight;
$("#rendered2").html("textarea scrollwidth "+ document.getElementById("ta").scrollWidth);
$("#rendered3").html("textarea...