I have a simple application where if the user presses TAB or Space; a new input field is added to a div element.
The following is a snippet of the div element used to hold the input fields:
<div class="container" id="container" onkeydown="KeyDown(event)">
<input type="text" maxlength="15" id="0"/>
</div>
The following is the JavaScript code I am using to add input fields:
function KeyDown(e) {
var container = document.getElementById("container");
if(e.which === 9 || e.which === 32) { //User pressed Tab or Space
container.innerHTML += "<input type='text' maxlength='15' id='0'/>";
}
}
This works, but there is a 8px margin/gap (4px more than default CSS) between the first and second text input fields. Only the first input field has an extra 4px margin, even though the CSS and HTML of the page is identical across all input fields in Chrome.
The problem is fixed by replacing the innerHTML of the container with the following Javascript:
if(c === 1) { //c is the number/count of input elements
container.innerHTML = "<input type='text' maxlength='15' id='0'/>";
}
...
c++;
Why does this occur while adding the initial input field with HTML, versus replacing the innerHTML and them incremental each input field?