HTML / CSS inline textarea set width to same as input - javascript

I'm not sure if this is possible by CSS alone, but I'm attempting to create an inline textarea element where the text is selectable but still looks like part of a sentence. It looks fine when the number of characters are known (cols="11") by:
<p>To run nload for your device run <textarea readonly cols="11">nload p3p1</textarea> in your terminal.</p>
and the CSS:
textarea {
display: inline;
border:none;
resize: none;
}
Is there a way of doing this dynamically, without specifying the columns for each textarea in CSS? So each textarea is inline and looks unobtrusively part of a normal paragraph but selectable? Failing a CSS solution, is there a (pure) JavaScript one?

You will need to render the input text and calculate the width of the input submitted text based on that render.
A possible sollution is to copy the text into a hidden span and check it's width as illustrated:
jQuery('input').on('input', function()
{
var $this = jQuery(this);
// Create a widthSpan if we haven't already.
document.$widthSpan = document.$widthSpan || jQuery('<span style="display: none" />').appendTo(document.body);
document.$widthSpan.text($this.val());
$this.css('width', document.$widthSpan.width() + 5);
}).trigger('input');
A working fiddle: http://jsfiddle.net/687uew37/.
Do note this is an example which updates as soon as the input's content is changed. Depending on the implementation and usage if this you might need to implement changes accordingly.

You can use JavaScript to dynamically set the width of your textarea depending on the number of characters inside your textarea.
HTML:
<p>To run load for your device run <textarea class="tx" readonly>nload p3p1</textarea> in your terminal.</p>
<p>Here is another example which follows the same pattern <textarea class="tx" readonly>your textarea query you can add lots of text. </textarea>You can add a lot of other stuff after it and it will still look like part of your text.</p>
CSS:
p{
line-height:1.5em;
font-size:14px;
}
textarea {
margin-bottom:-0.3em;
border:none;
overflow:hidden;
height:14px;
display:inline;
white-space: nowrap;
}
Jquery:
$(document).ready(function(){
$('textarea').each(function(){
//Width of a character:
var chars = 8;
//Find out how many characters are in the text area:
var txLength = $(this).val().length;
//Calculate the width:
var txWidth = chars * txLength;
//Set the width:
$(this).css({'width':txWidth,'resize':'none'});
});
});
You start by taking each textarea one at the time. The idea is that you already have a font-family predefined and you know the average width of the characters in your font-family. You can find your font-family average character width online or you can estimate if you don't know it (I took a guess here).
In this case the variable chars holds the average width value of the character. You then compute the desired textarea width by multiplying the number of characters with the average character width and insert that in your CSS using jQuery's .css() function.
Working fiddle here: http://jsfiddle.net/ys2Lfrt8/5/
Drawbacks: Not responsive but can be fixed using #media-queries

Related

Adjusting Field Height Dynamically With CSS

I have a textarea field, which I would like to automatically adjust according to number of lines used (i.e., if the user enters one line, the field height will show that line only, but if the user enters a long text, the field will show all the lines of text).
I would like it to happen dynamically, without using scroll (overflow).
I would appreciate help with this.
thanks
There are lots of ideas given in the answers pointed to in the comments so if you absolutely have to stick with textarea perhaps some of them will solve your problem but they require Javascript and I notice you have tagged CSS not JS.
So, have you considered using a contenteditable div instead? This will automatically resize depending on content without needing Javascript:
.input {
overflow: auto;
border: 1px solid black;
}
<div class="input" contenteditable></div>

How to change text to invisible, but still show underline?

I made a studying tool using Javascript and PHP. There's a toggle that shows/hides keywords in a paragraph, so the user can mentally "fill in the blanks".
How I've done this so far is that the all the keywords are underlined, and I use a DOM selector to select all innerHTML in u tags.
<p>
Example sentence, <u>this</u> is a <u>keyword</u>.
</p>
<button onClick='hideKeywords()'>Hide Keywords</button>
<script>
function hideKeywords() {
var x = Array.from(document.getElementsByTagName('u'));
for (var i = 0; i < x.length; i++) {
x[i].style.visibility = "hidden";
}
}
</script>
This works as intended - the "keywords" are blanked out and the flow of the document is unaffected, since the keywords still take up the same space that they would normally take.
One downside is that in paragraphs with particularly long "keywords", the paragraph's line structure is disrupted and it looks like text is just floating randomly in space. This would be fixable if I could somehow change visibility such that the words in the keywords are hidden and the text-decoration (underline) still shows. This retains the line structure.
I thought about using Javascript to replace every character in the keyword with underscores, but two more problems pop up. One thing is that even if the number of characters stay the same, the width might change.. For example, "apple" is not the same physical length as "______". This is not ideal as the document flow would change. A second problem is that I can't think of any way to get the keywords back after converting them into underscores.
One workaround is instead of changing the visibility to "hidden", I could change the background-color to the same color as the text. This blocks out the text, but the line structure and document flow are both preserved. However, I do hope to find a way to implement my original idea, so any suggestion is appreciated!
Update: I would prefer not to add any additional divs to the keywords. The user can add new entries using a rich text editor, so declaring a keyword is as easy as underlining it in the text editor.
You can do it with css adding a pseudo-element and instead of using visibility hidden, using color: transparent, like this:
u{
position:relative;
}
u::after{
content: ' ';
display:block;
position:absolute;
bottom:0;
left:0;
width: 100%;
height:1px;
background-color:#000;
}
And in the script
<script>
function hideKeywords() {
var x = Array.from(document.getElementsByTagName('u'));
for (var i = 0; i < x.length; i++) {
x[i].style.color = "transparent";
}
}
</script>
https://codepen.io/anon/pen/ROoMaM
I would probably implement this using your second method. Set the text colour to the same as the background then add a bottom border to the element. Preserves the spacing and allows you to quickly check if you are right by just highlighting the line. Also, if you give the keyword wrapper element a class you can easily just toggle the color of the hidden text, and retain the underlines so you can see what has changed.
div {
color: black;
}
span {
color: white;
text-decoration: none;
border-bottom: 2px solid green;
}
<div>
This <span>is hidden</span> with an underline
</div>
You'd have to find some way to get the div positioned under the hidden text, but you can use the following code to create a div with the width of the text. I might come back later after answering and find a way to position the div.
In your HTML, let's say you have a phrase, foo bar, that you want hidden. You will assign an id to it with the code: <p id="foo">foo bar</p>
Here is the CSS:
#foo {
position: absolute;
visibility: hidden;
height: auto;
width: auto;
white-space: nowrap;
}
Then in your Javascript, you can use the following code:
var fontSize = 20; //this defines a font size
var foo = document.getElementById("foo");
foo.style.fontSize = fontSize; //this sets the style as the font size
var width = (foo.clientWidth) + "px"
var div = document.createElement("div");
div.style.width = width;
div.style.height = 2px;
div.style.background = "red"; //makes the underline visible
document.getElementById("main").appendChild(div);
From here, you could probably just reposition the div how you want so it appears under the text. This way, the div is the exact length of the text.
An alternative solution would be to use a monospace font and then manually calculuate the width.

Input text field with auto width [duplicate]

Newbie CSS question. I thought width:auto for a display:block element meant 'fill available space'. However for an <input> element this doesn't seem to be the case. For example:
<body>
<form style='background:red'>
<input type='text' style='background:green; display:block; width:auto'>
</form>
</body>
Two questions then:
Is there a definition of exactly what width:auto does mean? The CSS spec seems vague to me, but maybe I missed the relevant section.
Is there a way to achieve my expected behavior for a input field - ie. fill available space like other block level elements do?
Thanks!
An <input>'s width is generated from its size attribute. The default size is what's driving the auto width.
You could try width:100% as illustrated in my example below.
Doesn't fill width:
<form action='' method='post' style='width:200px;background:khaki'>
<input style='width:auto' />
</form>
Fills width:
<form action='' method='post' style='width:200px;background:khaki'>
<input style='width:100%' />
</form>
Smaller size, smaller width:
<form action='' method='post' style='width:200px;background:khaki'>
<input size='5' />
</form>
UPDATE
Here's the best I could do after a few minutes. It's 1px off in FF, Chrome, and Safari, and perfect in IE. (The problem is #^&* IE applies borders differently than everyone else so it's not consistent.)
<div style='padding:30px;width:200px;background:red'>
<form action='' method='post' style='width:200px;background:blue;padding:3px'>
<input size='' style='width:100%;margin:-3px;border:2px inset #eee' />
<br /><br />
<input size='' style='width:100%' />
</form>
</div>
"Is there a definition of exactly what width:auto does mean? The CSS
spec seems vague to me, but maybe I missed the relevant section."
No one actually answered the above part of the original poster's question.
Here's the answer:
http://www.456bereastreet.com/archive/201112/the_difference_between_widthauto_and_width100/
As long as the value of width is auto, the element can have horizontal
margin, padding and border without becoming wider than its container...
On the other hand, if you specify width:100%, the element’s total
width will be 100% of its containing block plus any horizontal margin,
padding and border... This may be what you want, but most likely it isn’t.
To visualise the difference I made an example:
http://www.456bereastreet.com/lab/width-auto/
ORIGINAL answer using Angular: Because input's width is controlled by it's size attribute, this is how I initialize an input width according to its content:
<input type="text" class="form-list-item-name" [size]="myInput.value.length" #myInput>
UPDATE for JavaScript (10/01/2022): My original answer was from the time I was studying Angular. If you need pure, Vanilla JavaScript the solution is even simpler:
<input type="text" oninput="this.size = this.value.length">
Or add an "input" event listener to your input html element and run a code like this:
const myInput = document.querySelector('input');
myInput.addEventListener('input', this.typing);
(...)
typing(e) {
e.target.setAttribute('size', e.target.value.length);
}
Obs: Depending on the browser, input may restore to its default size of something between 150px and 250px if/when size gets the 0 value. In this case, just add +1 to value.length:
<input type="text" oninput="this.size = this.value.length + 1">
OR:
typing(e) {
e.target.setAttribute('size', e.target.value.length + 1);
}
As stated in the other answer, width: auto doesn't work due to the width being generated by the input's size attribute, which cannot be set to "auto" or anything similar.
There are a few workarounds you can use to cause it to play nicely with the box model, but nothing fantastic as far as I know.
First you can set the padding in the field using percentages, making sure that the width adds up to 100%, e.g.:
input {
width: 98%;
padding: 1%;
}
Another thing you might try is using absolute positioning, with left and right set to 0. Using this markup:
<fieldset>
<input type="text" />
</fieldset>
And this CSS:
fieldset {
position: relative;
}
input {
position: absolute;
left: 0;
right: 0;
}
This absolute positioning will cause the input to fill the parent fieldset horizontally, regardless of the input's padding or margin. However a huge downside of this is that you now have to deal with the height of the fieldset, which will be 0 unless you set it. If your inputs are all the same height this will work for you, simply set the fieldset's height to whatever the input's height should be.
Other than this there are some JS solutions, but I don't like applying basic styling with JS.
It may not be exactly what you want, but my workaround is to apply the autowidth styling to a wrapper div - then set your input to 100%.
If you're willing to include a little JavaScript to solve this, you can get exact sizing. This doesn't rely on approximating width with size or ems, doesn't rely on any hardcoded element widths, and works for e.g., type="number", which don't accept a size attribute.
The trick is to get your input sized exactly like a span with the same content, by actually having an invisible span with the same content.
Put your input inside a div along with a span that mirrors the input's value. Give both the input and the span the same styling, give the input 100% width, then hide the span and absolute-position the input to sit on top of the span.
This way, the container (and thus the input) are automatically sized by the visual appearance of the content of the invisible span.
https://codepen.io/spiffytech/pen/abwWRqo
<div id="relative-parent">
<span id="size-calibration"></span>
<input id="autosized-input" />
</div>
<style>
#relative-parent {
position: relative;
/* Have some width if the input is empty */
min-width: 1em;
/* Adjust size to match the span */
width: min-content;
}
#size-calibration {
visibility: hidden;
/* Prevent the span from wrapping the text when input value has multiple words, or collapsing multiple spaces into one */
white-space: pre;
}
#autosized-input {
position: absolute;
left: 0;
width: 100%;
}
#size-calibration, #autosized-input {
/* Normalize styles that the browser sets differently between spans and inputs.
Ideally, use a "CSS reset" here. */
font-family: "Arial";
padding: 0;
/* Demonstrate that this works for input with custom styles */
font-size: 24px;
}
</style>
<script>
function updateSize() {
const span = document.getElementById('size-calibration');
const input = document.getElementById('autosized-input')
span.innerText = input.value;
}
document.addEventListener('DOMContentLoaded', () => {
const input = document.getElementById('autosized-input');
input.oninput = updateSize;
// Provide some initial content
input.value = "I'm sized exactly right!"
updateSize();
})
</script>
After tried methods all above and failed, I workaround by modifying   width property in style by unit em:
tgt.style.width = `${(tgt.value.length + 1) / 2}em`
The only option I can think of is using width:100%. If you want to have a padding on the input field too, than just place a container label around it, move the formatting to that label instead, while also specify the padding to the label. Input fields are rigid.
Answer 1 - "response" gave a nice answer/link for it. To put it in short, "auto" is the default, so it is like removing any changes in the width of an element
Answer 2 - use width: 100% instead. It will fill the 100% of the parent container, in this case, the "form".
Using JQuery
$(document).on('input', '.input-fit-width', (e) => {
$(e.currentTarget).attr('size',e.currentTarget.value.length);
})
Nowdays, flex or grid makes it much easier , it overrides default style/behaviors of https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input#size which has a default value set at 20 see : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input#size
Giving you 2 plain CSS options without requiring JavaScript nor setting width to 100% and deal with box-sizing.
flex/flex-grow
<form style='background:red;display:flex;'>
<input type='text' style='background:green; flex-grow:1'>
</form>
grid
<form style='background:red;display:grid;'>
<input type='text' style='background:green;'>
</form>
Jquery way of adjusting size of input automatically.
In general:
$('#my_input_id').width( ($('#my_input_id').val().length) + "ch" );
On text input:
$(document).on("input", '#my_input_id', function () {
$(this).width( ($(this).val().length) + "ch" );
});
I think the simplest solution is to set parent element's width:
form{
width: 100%!important;
}

Horizontal Overflow/Text Inside Span nested inside Div

I'm trying to build a type of ticketing system, where each ticket is a div and has other, nested divs inside of it to better accommodate content. Aside from images and other types of media, it has a plain text area where a description of the ticket will go.
Everything works as it should, but when I print the description, the text continues horizontally, never vertically. This in turn produces a horizontal overflow and the div which contains that text apparently extends beyond the 100% width (which I understand fills its parents div width) I had assigned to it.
The text is inside a span tag, which is in turn inside the description div. I'm fetching that text from a JSON I receive client side, and I'm just concatenating, i.e. :
var description = receivedJson.description;
var desDiv = '<div class="description"><span>'+description+'</span></div>';
I think part of the problem is I'm concatenating all of it in a single line. Here's a demo, but again, since it's not dynamically substituting text, it kinda works and doesn't correctly reproduce the problem.
This is what's actually happening.:
I'm getting both scrollbars, when I only want the vertical one - if-and-only-if it's needed. Even if no text is present, I get scrollbars (probably cause of the padding I have on that span tag, but then how do I get spacing between the text and the div?).
How can I get the text to display vertically and only get a vertical scrollbar when the text exceeds the div's height?
.c span {
display: inline-block;
height: 100%;
padding: 1em 2em;
background-color: red;
}
remove width:100% . this should work fine :)

textarea immitation is not working well. any replacements?

I have this html and css: http://jsfiddle.net/b7rDL/6/
HTML:
<div class="text-block" contenteditable="true" spellcheck="false">Some Text</div>
css:
.text-block {
resize: none;
font-size:40px;
border: none;
line-height: 1;
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
min-width: 30px;
overflow: visible;
white-space: nowrap;
display: inline-block;
}
This code allows me to write text with no width limit or height limit. It displays no scroll bar and it grows with the text. Those are basically the features I need.
How can I convert this to regular textarea that will act the same? I want this to work on browser that doesn't implemented "contenteditable". Therefore I want to replace the div with textarea or other basiv element. How can I do it? (I don't mind using JavaScript).
How can I disable the spellchecker? spellcheck=false doesn't work. In the example, when I focus on the text box, I get that buggy red line. I am using Firefox.
How can I get rid of the border when I am focused? - SOLVED
I don't mind using JavaScript to solve those issues.
Any answer for those questions will help me.
Thanks
UPDATES:
#Oylex helped me with 3
#1
Working fiddle is here: http://jsfiddle.net/d9H9w/11/ (tested in IE8, Chrome and Firefox)
What you need is to set the width and height attributes as a user is typing within a text box.
Height
This is pretty straightforward:
Get the content of the textarea
Match for newline characters
Set the height to total number of newline characters(plus one for the first line and 1.5 for wiggle room) in em's.
Setting the height in em's makes this font-size agnostic, so it'll work with multiple font-sizes.
function getNewlines(){
// get the value(text) of the textarea
var content = textEl.value;
//use regex to find all the newline characters
var newLines = content.match(/\n/g);
// use the count of newlines(+1 for the first line + 1 for a buffer)
// to set the height of the textarea.
textEl.style.height = ((newLines && newLines.length || 0)+2.5)+'em';
};
Width
This is fairly easy, too, with one gotcha.
Get the content of the textarea
Split on newline characters to get an array consisting of lines of the textarea
Sort to get the longest line
Set the width to the length of the longest string in em's, multiplied by about .6(emRatio in my code), plus 2 ems for buffer space.
That last part is the kicker. The 'em' measurement is supposed to be a square representing the width and height that a single character takes up. This doesn't take kerning into account, so the height of a char is usually accurate, but the width is dependent on the chars around it. So, by guess and check, I figured that .6 em is about the average width of a character after kerning. .6 is pretty close, so I add 2 ems to the width for a bit of buffer space.
var emRatio = .6;
function longestLine(){
// get the value(text) of the textarea
var content = textEl.value;
// split on newline's. this creates an array, where each item in
// the array is the text of one line
var a = content.split('\n');
// use a sorting function to order the items in the array:
// longest string to shortest string
a.sort(function(a,b){return b.length - a.length});
// use the longest string * the emRatio to set the width
// Due to kerning, the letters aren't ever really 1em x 1em
// So I'm multiplying by an approximate ratio here (guess and check)
textEl.style.width = (a[0].length * emRatio + 2)+ 'em';
};
Existing problems with this implementation
To support resizing during long-held key presses, an onkeydown handler has to be included as well(this is not optimal for all cases that don't include long key presses)
All things considered, I think this fits what you need.
EDITS
Instead of having emRatio be .7, I changed it to .6 and added a buffer of 2 ems to the width. This addresses both issues #Naor mentioned in his comments.
I've updated the fiddle link and the Width section to reflect the changes.
EDIT 0
Request #1 Update
Working Solution: http://jsfiddle.net/7aeU2/
JQuery
$(function() {
// changes mouse cursor when highlighting loawer right of box
$("textarea").mousemove(function(e) {
var myPos = $(this).offset();
myPos.bottom = $(this).offset().top + $(this).outerHeight();
myPos.right = $(this).offset().left + $(this).outerWidth();
if (myPos.bottom > e.pageY && e.pageY > myPos.bottom - 16 && myPos.right > e.pageX && e.pageX > myPos.right - 16) {
$(this).css({ cursor: "nw-resize" });
}
else {
$(this).css({ cursor: "" });
}
})
// the following simple make the textbox "Auto-Expand" as it is typed in
.keyup(function(e) {
// the following will help the text expand as typing takes place
while($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
$(this).height($(this).height()+1);
};
});
});​
Request #2 Update
Also, here's a good explanation of why you can't outright disable spell check.
This does not belong to the realm of CSS (which is optional
presentational suggestions). It is not about stylistic features of
rendering data but about processing data interactively.
On browsers that support “spell checking” (which may involve grammar
and style checks), the HTML attribute spellcheck or the corresponding
IDL (DOM) attribute, settable in JavaScript, is effective.
In practice, those browsers tend to have “spelling checking” enabled
by default for textareas only, and as textareas normally contain human
language texts, turning it off does not sound useful. It is in any
case user-controllable (the user can switch it off or select
language).
via https://stackoverflow.com/a/9209791/1085891
Request #1
Simple Solution is pretty straight forward.
Working example: http://jsfiddle.net/b7rDL/12/
JQuery
$("#Solution0").keyup(function(e) {
while($(this).outerHeight() < this.scrollHeight) {
$(this).width($(this).width()+50);
};
});
HTML
<textarea id="Solution0" rows="1" style="height: 1.2em;"></textarea>
Fancier solution that will require some updating if you want the
width, rather than the height, to expand. Still, it's pretty nice.
http://jsfiddle.net/edelman/HrnHb/
https://github.com/ultimatedelman/autogrow
Other solutions - I know these all expand height. Let me know if you need width implementation of one of the below solutions.
http://bgrins.github.com/ExpandingTextareas/
http://blogs.sitepointstatic.com/examples/tech/textarea-expander/index.html
http://code.google.com/p/xautoresize-jquery/downloads/list
http://www.impressivewebs.com/textarea-auto-resize/
http://www.technoreply.com/autogrow-textarea-plugin-3-0/
Request #2
spellcheck="true" should work as described in the Mozilla docs: Controlling spell checking in HTML forms. It works for me in my first simple example running in Firefox 13.0.1. What version are you running?
for #3, the css option you are looking for is: outline: none;
I was having trouble figuring out the bounds of the textarea's content, so with this approach I'm copying the content of the textarea into a similarly styled p element, which is set to float: left; and then resizing the textarea based on the size of the p. This handles both width and height.
I've tested on Mac 10.8.1 FF 18.0, Safari 6.0, Chrome 25.0.1362.0 canary, iOS Safari 6.0.1 and iOS Simulator 5.1 (272.21). I don't have a PC or IE handy.
http://jsfiddle.net/b7rDL/34/
HTML
<textarea id="tx" class="text-block" spellcheck="false"></textarea>
<p id="dupe" class="text-block"></p>
CSS
.text-block {
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
resize: none;
font-size:14px;
border: none;
line-height: 1;
min-width: 30px;
overflow: hidden;
white-space: pre;
display: block;
outline: none;
width: 30px;
height: auto;
border: 1px solid #ddd;
background-color: #f7f7f7;
}
#dupe {
float: left;
display: none;
width: auto;
height: auto;
}
I added a background and border so I could see what's going on.
JavaScript
// no `var` so they are global and easier to work
// with in the inspector when using jsFiddle
$tx = $('#tx');
$dupe = $('#dupe');
lineH = Number($tx.css('line-height').replace('px',''));
update();
$tx.on('keydown', function() {
setTimeout(update, 0);
});
$tx.on('propertychange input keyup change', update);
function update() {
$dupe.text($tx.val());
$tx.css({
width: $dupe.width() + 7,
height: $dupe.height() + lineH
});
}
// not sure if this is needed, leaving it because
// I don't have many browsers to test on
$tx.on('scroll', function() {
tx.scrollLeft = 0;
tx.scrollTop = 0;
});
I'm adding extra space on the right and at the bottom because it seems to perform more consistently that way. Also, in the HTML, the wrap="off" is necessary for the version of Firefox, I'm using.
I got some good tips from this blog post.
Request #2
Working Demo
<body spellcheck="false">
<div class="text-block" contenteditable="true">
Some Text SpellCheck</div>
Hi Naor, The only problem with this thing is it will disable the spellcheck for all the elements in the <body> tag. If it doesn't matter you then you can go with it.
Your question is really interesting and challenging really liked it. I hope this may help you..!!
Best efficient way which was worked for me while I did something very close in the past was creating hidden out of flow div with the same exactly styles as the textarea has. And than setting out the timeout to update its html source based on information from textarea. This sounds bit scary but yet, after some testing and playing around nothing was better, that was already suggested, so just my variant.
http://jsfiddle.net/f2gAD/16/
and jQuery based script:
var textarea = $('textarea'),
textBlock = $('div.text-block'),
interval, value, freq = 10,
doTextAreaAdjust = function(){
textarea.css({
height: textBlock.outerHeight(),
width: textBlock.outerWidth()
});
};
doTextAreaAdjust();
textarea
.focus(function(){
interval = window.setInterval(
function() {
value = textarea.val().replace(/(\r\n|\n|\r)/gm, '[rnnr]');
value = value.replace(/</gm, '||'); // break html tags
value = value.replace(/\[rnnr\]/gm, '<br>');
value = value + '|'; // or <span>|</span> for better pixel perfect
textBlock.html(value);
doTextAreaAdjust();
}, freq
);console.log(interval);
})
.blur(function(){
window.clearInterval(interval);
});
​
For performance wise did it as self starting/stopping timeout on focus/blur, though here is yet some workaround is required. While testing in Chrome noted that interval not properly stopped if you made blur by clicking on another tab. So probably replacement for self calling function into the setTimeout will be better.
It works more or less fine in IE 7-8 which suppose the main targets but still some text jumps time to time occur, while for others it is okay, but guess you will use editable feature for modern browsers. Would recommend use modernizer for its detection.
Working here
http://jsfiddle.net/H2GSx/
Code here:
HTML:
<div style="overflow: scroll; width: 200px; height: 100px;">
<div class="text-block" contenteditable="true" spellcheck="false">Some Text</div>
</div>​
CSS:
.text-block {
resize: none;
font-size:40px;
border: none;
line-height: 1;
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
min-width: 30px;
overflow: visible;
white-space: nowrap;
display: inline-block;
}
​

Categories