Tom Tom - 27 days ago 7
CSS Question

positioning doesn't work with Javascript

I am building an "autofill" function. When the user types something in an input field and the system finds this string in the database it should display the string into the input field in grey, similar to what google used to/still have/has.

Therefore I built two input fields, one that's clearly visible:

html:

<input id="email_input" type="text">
<input id="autofill" type="text">


css:

#email_input{
background-color: transparent;
z-index: 100;
}


Then I position the
autofill
input via JS exactly where
email_input
is.

function positionAutocompleteInput(){
var top = $('#email_input').position().top;
var left = $('#email_input').position().left;
$('#autofill').css({'top':top});
$('#autofill').css({'left':left});
}
positionAutoFillInput();


The actual autfill I do like this:

function autofill(context){
var input = $('#email_input').val();
var replacement = context[0].email;
replacement = replacement.slice(input.length);
var display = input + replacement;
$('#autofill').val(display)
}


I tried calling
positionAutoFillInput();
onInput, so that it gets repositioned with each input. If I look at the positions of both input fields in the console, they both have the same positions.

Both input fields have the same font-size and font-family.

For some reason it still looks off:

enter image description here

Anyone know an answer?

Answer Source

Can you just position them with CSS like this? This way it requires no JavaScript to position it.

#autofill, #email_input {
  font-size: 20px;
}

#autofill {
  position: absolute;
  color: #CCCCCC;
}

#email_input {
  position: relative;
  z-index: 1;
  background: transparent;
}
<h1>Test</h1>
<div>
  <input id="autofill" type="text" value="1234567890">
  <input id="email_input" type="text">
</div>