tags:

views:

227

answers:

4

I would like to dynamically create a text box then dynamically position the text box. I have been able to dynamically create the text box with no problem but I have not been able to figure out how to position it. Any suggestions?

+2  A: 

Set the "top" and "left" positions? You may also need to set the "position" property to be "relative" or "absolute", depending on what you want to do.

Noon Silk
A: 

Position where?

Are you trying to position at some specific point or inside some other element? Try using position: absolute either in the CSS for your textbox class or use the style property on the object in the DOM.

Nick
A: 

There's a trick to positioning elements using javascript:

var el = document.getElementById('myelementID');
el.style.left = 10 + "px";
el.style.top = 10 + "px";

Note the ' + "px"' part of that. You need to make sure the expression is a string with units before the assignment takes place or it won't work reliably. You can also use the offsetTop and offsetLeft properties instead of the style, but the "string with units" rule still applies.

Joel Coehoorn
You also need to set the 'position' property to 'absolute', otherwise the 'left'/'top' properties won't do anything.
Reinis I.
I was figuring he'd already done that, but yes, that is necessary as well.
Joel Coehoorn
+1  A: 
var box = document.createElement('input'); // creates the element

box.style.position = 'absolute';  // position it
box.style.left = '100px';
box.style.top = '100px';  

document.body.appendChild(box); // add it as last child of body elemnt

If you want to add it somewhere else in the document hierarchy you have to find the parent using getElementById and use that elements appendChild function.

Tomas
This answer worked. Thanks a lot.
Weston Goodwin