Dynamically increasing textbox height? [duplicate] - javascript

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Autosizing Textarea
Hello all, I am trying to solve a problem and getting absolutely no where with it. What I am trying to do is dynamically change the height of an inputbox when the users text overflows it's width (sorta like Facebook's status update textbox).
You enter a brief update, and if the text is longer than the textbox, it creates a new row. I tried using a textarea, but for whatever reason cannot force it to be exactly 1 row by default.
Anyone know an easy way of doing this? :(

You can manually control the size of the textarea using the CSS height and width parameters. By binding a keypress event to the textarea, you can get the amount of text in the box and adjust the height accordingly. For example, here's some jQuery that will add 20 pixels to the height of the box for every 50 characters you put in:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
</script>
<textarea id="textbox" style="height:20px;width:400px;"></textarea>
<script type="text/javascript">
$(document).ready(function() {
$("#textbox").val('');
$("#textbox").keypress(function() {
var textLength = $("#textbox").val().length;
if (textLength % 50 == 0) {
var height = textLength/50;
$("#textbox").css('height', 20+(height*20));
}
});
});
</script>
You can tweak the values to get the desired effect.

To get the textarea to stretch, give this a go (jQuery): http://www.unwrongest.com/projects/elastic/.
As for the height of exactly one row, you could try rows="1" in the <textarea> tag, as well as removing CSS styling. Some browsers, however, may set a textarea's minimum height to more than one row.
Another solution would be to use a div on screen that, when the user clicks on it, makes the browser focus on a hidden textbox. The user types into the hidden text box, and the div is given the textbox's contents via. JavaScript. The tricky bit then is getting the flashing cursor, but you could use the pipe | character in the div and make it flash, although this starts getting long winded about the time you start it. I'd try with the textarea again personally :-)
Hope this helps,
James

Related

How to restrict the editing area in the ckeditor?

I am using ckeditor to edit my html text, here i want to restrict editable area in the ckeditor, i know how to give width and height for the ckeditor but i do not know how to give width and height for the ckeditor editing area.
Suppose if i give 700px width then user should enter the text only upto 700px, after that it should come to the next line.
I gave like below
CKEDITOR.replace( 'divedit', {
toolbar: 'Basic',
uiColor: '#9AB8F3',
width: '700px',
height:'200px'
});
but it is showing scroll bar if the user types text beyond 700px.
Sounds like a strange requirement. I would try this:
Before saving get the editor contents
Insert into a preview div that has the exact same CSS as your requirements / target but no width
Get the width of the content with javascript
Check if width > 700, alert message the user that their content Sucks and don't save
Otherwise, save
Don't do this with every change event - it will murder your performance at some point.
BTW, I never use static width content in CKE, so I cannot see how this is ever a problem, but I guess you have different requirements or something. If this is to stop users from entering OOOOOOOOOOOOOOOOOOOOOOOOOOOOO... or such content that overflow from the box you are outputting content with, don't worry about it. Content such as that should be deleted or edited using other means and you can also use CSS to control overflows. Or you can validate word widths with a max chars per word limitation or something.

Temporarily animate input type text when hovering

I want to show contents of an input type text if the text is wider than the current input width.
When I hover the field, I want the text to scroll to the left or something similar, in order to view the hidden text.
Thank you.
Note: tell me if I have to add/change the question's tags, please.
I thought about how I would do this and this is what I came up with.
On input hover I'm going to take the input value and put it in a div (or any other element). Then get the width of that div and compare it with the width of the input. If the div is wider than the input then I'm going to animate the inputs text-indent by the difference of the widths.
$('input').hover(function(){
var temp = $('div').html($(this).val()).width();
if($(this).width() < temp){
$(this).animate({
textIndent: $(this).width()-temp
}, 100);
}
});
You can see the full solution here: http://jsfiddle.net/taneleero/tB5C5/2/
Should be enough to get you going.
Eh, even though I did make that comment. couldn't resist this one myself. Using jQuery:
<input type="text" id="txt" value="A very long text goes here very long text goes here very long text goes here very long text goes here very long text goes here indeed."></input>
$('#txt').hover(
function() {
$(this).animate({"scrollLeft": this.scrollWidth}, this.value.length*50)
},
function() {
$(this).stop();
this.scrollLeft = 0;
}
)
here jQuery .animate() is used to animate .scrollLeft position of text within input field. Animation duration is tied to text length, so the speed should be the same for all kinds of texts. When mouse leaves input control - scroll position is reset to original.
Demo: http://jsfiddle.net/uPGmC/
If you googled a bit for "input text scroll left", you would find answers like this, combining it with jQuery docs on hover and animate you would piece the solution together yourself.

How to have transparent fonts except for the 'text-caret' in a textarea?

I have a simple textarea and I need to make transparent letters while allowing the text-caret to be visible. When I apply the following rules then I get invisible caret:
textarea {
background: transparent;
opacity: 0;
}
When I type invisible text, I need to see the text-caret move.
EDIT: I need to make editor to edit td cell in table. When I click on a cell I show a textarea and start typing. On a each character letter, I insert a context in a cell. After that, I hide a textarea.
This jsFiddle DEMO uses an online tutorial method that has been slightly modified to create a non-native browser text-caret along with transparent text.
Also, this jsFiddle New Method I created handles that goal differently but isn't IE8 friendly.
Status Update: I've improved the above jsFiddle DEMO with this newer version titled:
jsFiddle New Method that's Newer!!
The above jsFiddle version now allows the inside of the text-area to be clicked and the caret will respect that clicked location. This extra functionality was made possible by a great question and answer here.
Time to throw my $0.02 in.
This is an answer to the question, as I understood it, that works, it's quick and dirty, so feel free to make suggestions. This code is untested, but I did create a working fiddle here: http://jsfiddle.net/66RXc/
<html>
<head>
<title>Testing</title>
<script type="text/javascript">
<!--
function call(val) {
document.getElementById('result').value += val.charAt(val.length - 1);
document.getElementById('result').value =
document.getElementById('result').value.substr(0, val.length);
document.getElementById('test').value =
document.getElementById('test').value.replace(/[^\^]/g, ' ');
}​
-->
</script>
</head>
<body>
<textarea name="textarea" cols="20" rows="5" id="test"
onKeyUp="call(this.value);"></textarea>
<textarea style="display:block" cols="20" rows="5" id="result" disabled>
</textarea>​
</body>
</html>
The way I approached it was every time a character is typed in textarea "test", copy it over to a hidden text box, and replace all the characters in "test" except ^ with spaces. The characters are hidden, and the carat is still there. The full text is still in the other box. You could use display:hidden instead of display:block to hide it.
This isn't exactly the best implementation in the world, just something I did quickly. You have to type kind of slow (~15-20 WPM) for it to work.
Here is a CSS3 solution for making the text, itself, transparent:
Set the color attribute to be color: rgba(0,0,0,0); for the text
The only problem is that the caret goes invisible to. I did a quick search and found out that the caret and its styling are completely at the disposal of the browser. As such, the only option that I can think of for you is to use Javascript to add a simulated caret to the end of what you are typing.
I have an idea of how to do this, but it's messy and I wouldn't exactly call it ideal - I am, however, going to write it in case it helps further someone else's idea:
add a hidden label to the page
make sure it's hidden and not display: none; (so that it has actual width)
set white-space: nowrap; to keep it all on one line)
make sure the text is styled exactly the same as the text in the textarea
add the element <span id="caret">|</span> right before the textarea (I will refer to this as the caret for the rest of the spec)
set its position to position: relative;
increase its z-index to make it overlay
shift it right in order to set it on top of where the ACTUAL caret's initial position would be
make a function to check take in the value of the textarea and check the width of the textarea against the position of the caret (lookup selectionStart if you don't know how to do this)
the problem here is that characters are not always the same length, nor are they always the same length as their counterparts in other fonts
to solve this, as text is entered into the textarea you should have it imitated in the hidden label you created in step 1
imitate only the text from the start of the textarea to the caret's current position
wrap each character (including spaces) in their own span
next you will have to call a function to compare the width of the label with the width of the textarea
if the label is less wide than the textarea, get the width of the last span in the hidden label and shift the caret to the right by that width, then move on to step 4
as this is function will be run as text is entered it will happen one character at a time
be careful here that the caret doesn't go outside the textarea when it's in its last and near last positions
if the label is wider than the textarea:
add the widths of the characters (spans) in the label one at a time until you reach the width of the textarea
shift the position of the caret down by the height of the font and back to the horizontal starting position (as the caret's position is relative, just change its left position back to (0 + offsetToACTUALCaretPosition)
use a flag (e.g. class="break") to mark the last span (character) in the previous row
call the width comparison function again
make sure that you include a condition to check for the flags that you added at the end of each "row" (if any)
if you haven't already, apply any desired CSS styles to the caret span and change the color of the textarea's text to be color: rgba(0,0,0,0);
Caveats:
this will have a lot of overhead for the tiny job it does
you will have to adjust this method to account for padding
you will have to adjust this method to add support for deleting characters and moving the carets to an earlier position (to the left)
if you leave the textarea scrollable, you will have to add support for that (also for similar settings, like static heights causing text to scroll or move off screen/out of the textarea's visible area)
As I said before, I know that this solution is very rough, but it may help someone come up with a better one.
Good luck!
Based on your edit, if you need to just hide a textarea why don't you use jQuery $('#your_id').hide();

How to find absolute or relative position of last letter inside an input field?

Maybe this is a strange question. Please, check Bellow you will understand.
Empty input type text, width=200px :
[____________________________]
Filled input type text, width=200px :
[abcdefg_____________________]
If input left is 0 how to find the absolute or relative position where the g letter is???
When user enters some text I want to display under last letter a simple div...
The text size hacks are OK, but you could alternatively use a visiblity: hidden span that moves your info div. HTML snippet follows:
<div><input type="text" value="hgello!!" onkeydown="document.getElementById('spacer').innerHTML = this.value;" /></div>
<div><span id="spacer" style="visibility: hidden;"></span>Character</div>
This way you can rely on the browser rendering the same font in roughly the same way into a span.
I can only think of one way to reliably do this, and it's quite dirty.
1) Use a content editable div floated left:
2) surround that div with another with a width of 200, border, and onlick sets focus to the editable div
3) put the div you want to show after the last letter after the editable div, also floated left
Result:
http://jsfiddle.net/tybro0103/zMezP/1/
Click on the box and start typing. The green box will move along with the cursor position.
In order to use this as a text field in a form you'll need to make a hidden input field. On form submit set the hidden field's value to editable div's inner html.
There is no built in "textWidth" param, sadly. However, a hack that will work pretty well: you can count the characters, guess at their width, and set your div "left" param equal to the character count * width (and make sure its absolutely positioned). something like:
var characterWidth = 6.8; //have to guess at this until it works...
var targetLocation = document.getElementById('yourInput').value.length * characterWidth;
document.getElementById('yourDiv').style.left = targetLocation + "px";
Run this script on a timer, every half second or so (or animate to the target location with jquery) and you should be in business.
Hope that helps.
As noted - this will only work if the font is monospaced and the user doesn't modify font size at all.
The only way I konw how to do that is to calculate the width of a letter then multiply it by the number of letter in your input.
Or
in a display:none div create a input width the maxlength attribute to the number of character in the current input. Then get the width of it.
set font size to input
make screenshot of input with text and see how much px used for 1 symbol (average)
count symblos * average width of 1 + input left padding = what you want :)
easy solution
I'm not really sure of the question but in my opinion you could do something like:
var len = 0;
$(document).ready(function(){
len = $('#input').val().length;
}
Now you could prepend the no of white spaces equal to the length in your target div.
Inspired by tybro's answer, I came up with this, which solves a problem in your question. If the textbox is a fixed length, what happens if the last letter is not visible at all? What co-ordinate should be reported then? Anyway, this gets around it by expanding the textbox indefinitely.
// markup
<div id="textbox">
<span id="edit" contentEditable></span>
<span id="end"></span>
</div>
<div id="report">x:? , y:?</div>
// css
#textbox {
border: solid black 1px;
min-height: 1em;
white-space: nowrap;
}
// javascript
$(function() {
$('#textbox').click(function() {
$('#edit').focus();
});
$('#edit').keypress(function() {
var endoff = $('#end').offset();
$('#report').html('x:' + endoff.left + ' , y:' + endoff.top);
});
});
The only thing I'm not sure of is when does keypress fire if it's before the content has changed, that's a problem. You could get round it by introducing a timeout or probably theres an even better solution. Unfortunately the keyup event doesn't seem to work on contentEditable things (in Firefox 5 anyway).
Hope this helps.

Finding width of text in Javascript [duplicate]

This question already has answers here:
Calculate text width with JavaScript
(29 answers)
Closed 10 years ago.
Is there a way to find the width of text in Javascript (jQuery is used, so happy to take advantage of any functions they provide) for a hidden element?
I want to have a graph of nodes. Each node has text inside and I want the nodes to have a width that accommodates the text up to a limit. So I essentially create hidden <div>'s with some html inside. Then I use jQuery to display those <div>'s on the graph at the right spots. It's important that I know the correct width ahead of time so I can construct the graph properly.
UPDATE: Just to clarify, I need to know how wide some text is while it's hidden. Blender gave an answer below, I'm hoping there's a less tricky way?
What width do you mean? If you mean the <div> element's width, there's a handy function which does just what you need. Play with some of these:
$('#foo').width();
$('#foo').innerWidth();
$('#foo').outerWidth();
As for finding the width of a hidden element, I usually do this dirty trick:
var zIndex = $('#foo').css('z-index');
$('#foo').css('z-index', '-10');
$('#foo').css('position', 'absolute');
$('#foo').css('display', 'block');
var fooWidth = $('#foo').width();
$('#foo').css('display', 'none');
$('#foo').css('z-index', zIndex);
There must be a simpler way, though...
$('#txt').width()
http://jsfiddle.net/Detect/jk97D/
You can set the style of the divs to have no wrap white-space:nowrap (so, text is in one line) then get the width of each div, if more than the limit, set it to the limit and set the style to allow text wrapping `white-space:normal
Just throwing in a non-JQuery answer to this. Assume I have a work div with id myworkerdiv and i have put my text in already.
var myDiv document.getElementById('myworkerdiv'),
width = myDiv.clientWidth || myDiv.scrollWidth;
You can also find out height as well, if your so included (clientHeight || scrollHeight).
You could use something similar blender's method, but use the visibility css property rather than display. Visibility:hidden; keeps placement of the element, but just makes it invisible.

Categories

Resources