JSFiddle - React, Tailwind, and code Playground
by Johan Preynat
HTML
<textarea id='area' placeholder='Your text here'>
</textarea>
CSS
#area {
/* Override needed textarea customized in iframe.css */
width: 300px;
height: 300px;
border: 0;
padding: 0;
margin: 0;
background-color:rgb(0,0,0);
background-color:rgba(0,0,0,0.5);
position : absolute;
outline:none;
resize:none;
overflow: hidden;
vertical-align: top;
text-align: center;
letter-spacing: 2px;
font-size: 17px;
}
JavaScript
$.fn.realHeight = function(textArea) {
return parseInt(textArea.css('height'), 10)
- parseInt(textArea.css('padding-top'), 10)
- parseInt(textArea.css('padding-bottom'), 10);
}
$.fn.realWidth = function(textArea) {
return parseInt(textArea.css('width'), 10)
- parseInt(textArea.css('padding-left'), 10)
- parseInt(textArea.css('padding-right'), 10);
}
$.fn.textWidth = function(textArea) {
if (!$.fn.textWidth.fakeEl) {
$.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
}
$.fn.textWidth.fakeEl.text(textArea.val())
.css('font-family', textArea.css('font-family'))
.css('font-size', textArea.css('font-size'))
.css('font-weight', textArea.css('font-weight'))
.css('letter-spacing', textArea.css('letter-spacing'));
return $.fn.textWidth.fakeEl.width();
};
$.fn.nbLines = function(textArea) {
var width = $.fn.realWidth(textArea);
var textWidth = $.fn.textWidth(textArea);
console.log('w: ' + width);
console.log('tw: ' + textWidth);
if(textWidth == 0)
return 1;
else {
var ratio = textWidth / width;
if (ratio == parseInt(ratio))
return ratio;
else
return 1 + Math.floor(ratio);
}
}
var textArea = $('#area'),
textAreaHeight = $.fn.realHeight(textArea);
textArea.css('font-size', textAreaHeight);
textArea.on('keyup', function(e) {
//e.preventDefault();
var width = $.fn.realWidth($(this));
var height = $.fn.realHeight($(this));
var textWidth = $.fn.textWidth($(this));
var maxFontSize;
//console.log(textWidth);
//console.log('nbl: ' + $.fn.nbLines($(this)));
var expectedNbLines = $.fn.nbLines($(this));
var lineHeight = $(this).css('line-height');
console.log(lineHeight);
var overflow = $.fn.textWidth($(this)) % width;
if...