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?
There will be whitespace between the two input tags (line break and spaces for your formatting). This will cause a single space to be rendered which will be your extra 4px. It should work if you change your initial html to:
Horrible formatting but a line break within a tag is not formatted.
I think that if you append the new input instead of manipulating the
innerHTMLyou might also, avoid the whitespace:By the way, a numeric id is not valid – it should start with a letter What are valid values for the id attribute in html.