How to calculate max-height with using max-length property in Textarea - javascript

in the above example,input has max character length so user can not able to write anymore. So I have to don't allow resizing beyond 200 characters since that is max for this field. So i think need to calculate max-height property.
Pass maxLength property is 200 , line-height is 18px. Is there any way to calculate max height with these values ?
i found an example here but it doesn't work for me.

You should probably think about contenteditable. Add a few event listeners and you've got a dyanmically sized text area.
contenteditable on MDN
Making content editable also on MDN
To do what you want has too many variables to be done "properly" and the needed size of the textarea will depend on a number of factors such as the font being used, the size of the font.
Of course the content itself would also affect the required size, add a few new lines and you'll need even more height.
The mix of characters would also affect the needed size i.e. capital x's X and m's M take up much more space than periods '.' . and i's i (assuming a variable width font.)
.editable {
border: 1px solid black;
min-height: 1em;
}
<div contenteditable="true" class="editable">
This text can be edited by the user.
</div>

Related

How to make dots on input PIN showing character amount to provide?

I need to create input with dots showing amount of characters required, and to hide one after other when characters provided:
What is the best way to do this?
I haven't come up with anything smart but drawing circles with position: absolute and add/remove them with js (on keydown or change). But that could fail, because of difference of character width (for ex. i and W)
Because #Santi proposed you the solution with jQuery, I've made a jsFiddle with usage of angular.
<div ng-controller="MyCtrl">
<span class="mask">•••••</span>
<span class="hider">{{val}}</span>
<input type="text" class="code" ng-model="val" maxlength="5" />
</div>
So I've created input which has no border and outline.
Below it on the bottom there is a span mask which has dots that you want. And above mask there is a hider where angular writes value from input so the background rise with the content and hide dots in mask span.
If you use angular in your project you could probably change my jsFiddle to directive.
Additionally IMHO it could be easly changed to jQuery option or even to pure javascript;
PS. Please be respectful for me, because I'm not very best in css.
If you set the font-family of your input field to a monospace font, for example Courier, every character will be the same size. Then you can size your dots based on the ch unit. 1ch is the width of the 0 character (and thus every character in a monospace font).
If you don't want to draw circles, you might be able to use JavaScript to swap out bullets (•) each time a new character is input.
I think your easiest and cleanest method might be implementing something like MasekdInput. Check out the Demo section towards the bottom.
It's a JQuery plugin that puts placeholders into your inputs, and allows you to specify the placeholder character. By default it's _, but you could easily change it to be • by doing the following...
$("#myTextField").mask("*****",{placeholder:"•"});

Restrict user input to fixed width and height contenteditable div

After a lot of research, I haven't found a post with exactly the same requirements so I thought write a new post.
I'm trying to create a fixed area (e.g. 200px by 300px) where the user can enter text input. He should be able to enter any character (including line breaks).
However, he should not be able to 'write outside the box' (i.e. there shouldn't be overflow scroll or hidden for the 200x300 area).
Once user reaches the 'bottom' of the area, they can't enter any more line breaks.
And once they reach the 'bottom right' corner of the 200x300 area, they shouldn't be able to enter any more characters at all.
Is this possible in css, angular, js, jquery, etc?
Limit the length of characters with base in font and div's size, but you must change the font size and family or line height because every browser can have different styles.
To limit the length of characters in the div is need to ignore the HTML tags in the content, like interpreting.
Firstly calculate how many characters fits there.
You can restrict the number of characters per line with the cols="" attribute and set the displayed the number of editable lines with the rows="" attribute. However limiting the number of rows could only be one with the maxlength attribute which would control the number of characters you can have, which you'd have to estimate. There are some hacks to limit the number of rows with event listeners, but they seem to have fairly major bugs.
It is possible, you just need to do following:
Use event handlers to control character input process. It is required to be able to stop processing further keystrokes when limit is reached. Use keypress and keydown, first handles character processing, second - control keys processing.
Each time user presses a key, use a separate buffer to produce final result, compute its bounding rectangle, and if it is bigger than limit, prevent event handling.
Height of text body could be calculated by multiplying number of lines by line height (interpret font-size and line-height CSS properties).
Width of text body could be computed rather easy with help of HTML5 canvas measureText method.
If you don't have canvas, you can use offscreen span (or any other inline) element - just fill innerHTML with text block and use its offsetWidth attribute. Actually, if you replace line break characters with <br>, you may use span approach to get both dimensions in one go - just make sure it has same style as editable container.
ContentEditable containers, as i remember, store text body in HTML format already (in other words - with <br>s instead of line break characters).

Find the width of an auto sized element

Basically I need the width of a span. Do to the need to use several custom characters that are not found on a keyboard I am building my own "input" field, using a "div". Each character gets wrapped in a "span" tag that has an event listener attached. This will allow the user to click anywhere in the string and have the cursor move to a position after a character, it also allows them to add or delete characters in the middle of a string.
I am using "offsetLeft" and "offsetWidth" to find the right side of a character, the problem is when a character/span is clicked the "offsetWidth" is way off. So for example, if I am using a 14 pixel font an "M" will return as 35 pixels wide when it is actually 11 pixels. And there are several variations, an average sized character like an "S" will return at 26 pixels when it is actually 9. So there is variation in the sizing. Now you may wonder how I found the actual letter size and that was using Firebug. Which if Firebug can find it I would assume so can I, I just haven't figured out how. So I hope someone here knows.
I also tried using "getComputedStyle" and "currentStyle to find the width and it returns "auto". Also tried getBoundingClientRect().width it the same as offsetWidth, the difference being that it also finds the fractions of a pixel in width, so an "M" is 35.366668701171875 pixels wide, odd.
EDIT:
Based on user1289347 post I should have noted that the "offsetWidth" causes the "offsetLeft" to be off by the errant amount as well.
Try jquery width() it computes the dom width pretty well every time I've used it. http://api.jquery.com/width/
And if jquery is out of the question
Create a DIV styled with the following styles. In your JavaScript, set the font size and attributes that you are trying to measure, put your string in the DIV, then read the current width and height of the DIV. It will stretch to fit the contents and the size will be within a few pixels of the string rendered size.
HTML:
<div id="Test">
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</div>
CSS:
#Test
{
position: absolute;
visibility: hidden;
height: auto;
width: auto;
}
JavaScript (fragment):
var test = document.getElementById("Test");
test.style.fontSize = fontSize;
var height = (test.clientHeight + 1) + "px";
var width = (test.clientWidth + 1) + "px";
This will create a seperate testable div with your test, credit here Calculate text width with JavaScript It's a lot of work but it should get you better results by operating outside of your existing markup.

How to calculate total width of text including the left and right bearing

I am trying to calculate the total width of a span in HTML including both the left and right bearings of the first and last characters. I have already tried Javascript's offsetWidth and jQuery's width & outerWidth functions, but neither of them return the correct value I am seeking. Here is an example of what I mean. Running in Firefox the calculated width is 135px, while measuring with the Web Developer plug-in gives an actual width of 141px.
Edit
Here is what I've tried, and here are the values it gives me:
offsetWidth = 135
jQuery.width() = 135
jQuery.outerWidth() = 135
None of them are calculating the 6px overhang on the 'f' (which would make the width 141).
Sadly, no straightforward solution exists because it is outside the realm of the box model -- the browser itself does not recognise the overhang of the letter 'f' when rendering layout. You can see this for yourself if you wrap the <span> within a <div> of width: 135px, and overflow: auto -- No scrollbars appear, the overhang is simply cut off. This is also why firebug reports the width without the overhang.
As #Aaron pointed out, the problem doesn't exist with monospaced fonts as no letters extend beyond the character's fixed-width box in those fonts.
The only way to find the real width is through pixel-based (rather than layout-based) methods. I can think of one way: draw the same text, with the same font, onto a <canvas> element, and measure the pixel width that way.
Actually, I think the problem is the font itself. I changed the jsfiddle to font-family: monospace, and it was all contained within the grey box (and calculated correctly, as a result). Even leaving it as the original font, but changing the sample to "aaa" or "mmmm" worked great. It's just the "f" glyph in that font that's blowing it for you.
Unfortunately, I don't know of a DOM attribute that accounts for that. Not sure that's much of an answer, but I don't have access to comment on the question and thought these findings might help point you in the right direction...
How about jQuery's .width()?
<span id="spanId"> ... </span>
and
var w = $('#spanId').width();

How do you find the largest font size that won't break a given text?

I'm trying to use CSS (under #media print) and JavaScript to print a one-page document with a given piece of text made as large as possible while still fitting inside a given width. The length of the text is not known beforehand, so simply using a fixed-width font is not an option.
To put it another way, I'm looking for proper resizing, so that, for example, "IIIII" would come out in a much larger font size than "WWWWW" because "I" is much skinnier than "W" in a variable-width font.
The closest I've been able to get with this is using JavaScript to try various font sizes until the clientWidth is small enough. This works well enough for screen media, but when you switch to print media, is there any guarantee that the 90 DPI I appear to get on my system (i.e., I put the margins to 0.5in either side, and for a text resized so that it fits just within that, I get about 675 for clientWidth) will be the same anywhere else? How does a browser decide what DPI to use when converting from pixel measurements? Is there any way I can access this information using JavaScript?
I would love it if this were just a CSS3 feature (font-size:max-for-width(7.5in)) but if it is, I haven't been able to find it.
The CSS font-size property accepts length units that include absolute measurements in inches or centimeters:
Absolute length units are highly dependent on the output medium, and
so are less useful than relative units. The following absolute units
are available:
in (inches; 1in=2.54cm)
cm (centimeters; 1cm=10mm)
mm (millimeters)
pt (points; 1pt=1/72in)
pc (picas; 1pc=12pt)
Since you don't know how many characters your text is yet, you may need to use a combination of javascript and CSS in order to dynamically set the font-size property correctly. For example, take the length of the string in characters, and divide 8.5 (assuming you're expecting US letter size paper) by the number of characters and that gives you the size in inches to set the font-size to for that chunk of text. Tested the font-size with absolute measurements in Firefox, Safari, and IE6 so it should be pretty portable. Hope that helps.
EDIT: Note that you may also need to play around with settings such as the letter-spacing property as well and experiment with what font you use, since the font-size setting isn't really the width of the letters, which will be different based on letter-spacing, and font, proportional to length. Oh, and using a monospace font helps ;)
I don't know of a way to do this in CSS. I think your best bet would be to use Javascript:
Put the text in a div
Get the dimensions of the div
Make the text smaller if necessary
Go back to step 2 until the text is small enough
Here's some sample code to detect the size of the div.
Here's some code I ended up using, in case someone might find it useful. All you need to do is make the outer DIV the size you want in inches.
function make_big(id) // must be an inline element inside a block-level element
{
var e = document.getElementById(id);
e.style.whiteSpace = 'nowrap';
e.style.textAlign = 'center';
var max = e.parentNode.scrollWidth - 4; // a little padding
e.style.fontSize = (max / 4) + 'px'; // make a guess, then we'll use the resulting ratio
e.style.fontSize = (max / (e.scrollWidth / parseFloat(e.style.fontSize))) + 'px';
e.style.display = 'block'; // so centering takes effect
}

Categories