javascript - Set textarea exact width, based on number of chars -
having following problem.
i have limit users maximum number of chars, per line, on textarea, seems cols not trick, when including vertical scrollbar:
.textarea1 { resize: none; font-family: monospace; }
when no scrollbar visible, works fine using 50 chars. <br /> <textarea class="textarea1" cols="50" rows="3">123456789!123456789!123456789!123456789!123456789!</textarea> <br /> in case, when scrollbar visible, @ least 3 chars go next line. <textarea class="textarea1" cols="50" rows="3">1234567890123456789!1234567890123456789!123456789!123456789!1234567890123456789!1234567890123456789!123456789!1234567890123456789!123456789!123456789!123456789!123456789!123456789!123456789!123456789!</textarea> <br /> in case, when use 10 chars, can fit 1 char on each line. <br /> <textarea class="textarea1" cols="10" rows="3">123456789!</textarea> <br /> in case, scrollbar visible, 1 char go next line. <br /> <textarea class="textarea1" cols="10" rows="3">123456789!123456789!123456789!123456789!123456789!</textarea>
i considered calculating width of textarea, exemplified pseudo code.
scrollbarwidth + textareaborderwidth + (nchars * singlecharwidth)
but no dice, it's big smaller lines (10 chars) , small when using 50 chars.
need support ie10+, ch units no go. besides support ch on ie11 doggy least.
any solutions?
this should work you. tested on chrome however.
function scrollbarvisible(element) { return element.scrollheight > element.clientheight; } $.each($("textarea"), function(index, value){ var cols = value.getattribute("cols"); if (cols > 0){ if (scrollbarvisible(value)){ cols = parseint(cols) + 3; } $(value).css("width", cols + "ch"); } })
.textarea1 { resize: none; padding: 0; display: block; line-height: 1; resize: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> when no scrollbar visible, works fine using 50 chars. <br /> <textarea class="textarea1" cols="50" rows="3">123456789!123456789!123456789!123456789!123456789!</textarea> <br /> in case, when scrollbar visible, @ least 3 chars go next line. <textarea class="textarea1" cols="50" rows="3">1234567890123456789!1234567890123456789!123456789!123456789!1234567890123456789!1234567890123456789!123456789!1234567890123456789!123456789!123456789!123456789!123456789!123456789!123456789!123456789!</textarea> <br /> in case, when use 10 chars, can fit 1 char on each line. <br /> <textarea class="textarea1" cols="10" rows="3">123456789!</textarea> <br /> in case, scrollbar visible, 1 char go next line. <br /> <textarea class="textarea1" cols="10" rows="3">123456789!123456789!123456789!123456789!123456789!</textarea>
Comments
Post a Comment