Jump to content

Make input field Expand onkeyup


unemployment

Recommended Posts

I am trying to make an input area expand onkeyup but my function appears to be broken.  Happen to know the fix?  It starts to fail at current.onkeyup = current.onchange = function(e)

 

var minSize = 10; //Minimum size input can be in pixels
	var increment = 7; //Increase in size per character typed

	var inputs = document.getElementsByTagName('input');

	for(var i = 0; i < inputs.length; i++)
	{
		 var current = inputs[i];
		 if((' ' + current.className + ' ').indexOf('input_variable_width') > -1)
		 {
				current.onkeyup = current.onchange = function(e) {
					   var target = e ? e.target : window.event.srcElement;

					   target.style.width = (minSize + increment * (target.value.length-1));
				}
		 }
	}

Link to comment
Share on other sites

I would aim for something more like this:

1. Detects the class a little better (works if you also had a class like "input_variable_width2")

2. Uses .size instead of a pixel width. If not that then at least use ems.

3. Uses onkeydown (because onkeyup happens when the key is released and onchange for inputs happens onblur)

// measured in characters:
var minSize = 1;
var maxSize = 10; // a good idea to have one

var inputs = document.getElementsByTagName("input");
for (var i = 0; i 	var current = inputs[i];
if ((" " + current.className + " ").indexOf(" input_variable_width ") >= 0) { // note the spaces
	current.onkeydown = function() {
		this.size = Math.min(maxSize, Math.max(minSize, this.value.length));
	};
}
}

Untested, naturally.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.