1

I try to create input controls dynamically , works fine apart from the positioning, for some reason I cant put the elements under the previous one, because I'm unable to get "style.top" property. What I'm doing wrong and how can I fix it?

the HTML code:

<div id='div_attach' class='scrollbox' style='top: 380px; height: 65px; left: 100px; right: 135px;'>
  <a href='goes_nowhere' style='top: 5px; left: 5px;'>click_me_if_you_dare</a>
</div>
<button type='button' style='top: 380px; width: 120px; right: 10px; height: 20px;' onclick='createFileInput("div_attach");'>new input</button>

the JS code:

function createFileInput(parentID) {
  var atop, index;
  var parent = document.getElementById(parentID);
  var control = document.createElement('input');

  control.setAttribute('type', 'file');
  elements = parent.getElementsByTagName('*');

  // debug only ...
  for (index = 0; index < elements.length; ++index) {
    alert(elements[index].style.top);
    alert(elements[index].style.height);
  };

  if (elements.length > 0)
    atop = elements[elements.length - 1].style.top + elements[elements.length - 1].style.height + 5;
  else
    atop = 5;
  control.setAttribute('name', 'FILE_' + elements.length);
  control.className = 'flat'; 
  control.style.left = 5 + 'px'; 
  control.style.top = atop + 5 + 'px'; 
  //  control.style.top = (elements.length * 30) + 5 + 'px'; 
  control.style.width = 500 + 'px'; 

  parent.appendChild(control);
  control.focus();
}
tcxbalage
  • 696
  • 1
  • 10
  • 30

1 Answers1

4

The code:

atop = elements[elements.length - 1].style.top + elements[elements.length - 1].style.height + 5;

will return something like "5px5" because it's a string to which you append 5.

Replace it with

atop = parseInt(elements[elements.length - 1].style.top, 10) + parseInt(elements[elements.length - 1].style.height, 10) + 5;

Make sure those element have a top and height value, or else parseInt() will return NaN.

edit: In the example, the <a> has no height.

Skwal
  • 2,160
  • 2
  • 20
  • 30