JSFiddle - React, Tailwind, and code Playground
by andrei
HTML
<input type="text" id="text" />
<div id="currentWidth"></div>
<textarea id="text2"></textarea>
CSS
#text {width:200px;}
#test {display:inline-block; position:absolute; left:-5000px; white-space:no-wrap; border:1px solid red;}
#test-textarea {display:block; position:absolute; left:-5000px; border:1px solid red; word-wrap:break-word; white-space:no-wrap; overflow:auto}
body {position:relative}
#text2 {width:200px; height:100px; margin-top:10px}
JavaScript
$("<div/>", {
id: 'test'
}).appendTo("body");
$("<div/>", {
id: 'test-textarea'
}).appendTo("body");
//inputbox
(function() {
var AVAILABLE_HORIZONTAL_SPACE = 100,
input = $("#text"),
testDiv = $("#test"),
widthContainer = $("#currentWidth");
input.bind("keyup", function() {
var currentWidth;
testDiv.html($(this).val());
currentWidth = testDiv.width();
widthContainer.html(currentWidth + "px");
if (currentWidth > AVAILABLE_HORIZONTAL_SPACE) {
alert("Maximum reached! Current number of characters:" + input.val().length);
}
});
})();
//textarea
(function(){
var AVAILABLE_VERTICAL_SPACE = 100,
AVAILABLE_HORIZONTAL_SPACE = 100,
input = $("#text2"),
testDiv = $("#test-textarea");
testDiv.css({
width: AVAILABLE_HORIZONTAL_SPACE,
height: AVAILABLE_HORIZONTAL_SPACE
});
input.bind("keyup", function() {
testDiv.html($(this).val());
if (testDiv[0].clientHeight < testDiv[0].scrollHeight) {
alert("Maximum reached! Current number of characters:" + input.val().length);
}
});
})()