Autocomplete positioning
Fiddling with the following question on SO: http://stackoverflow.com/questions/12901637/javascript-get-the-absolute-position-in-px-of-a-caret-in-a-input-text-or-texta
HTML
<div id="container">
<input type="text" id="foo">
<div id="ac"></div>
<span id="dummy"></span>
</div>
CSS
body { padding: 15px; }
.hidden { display: none; }
#container {
position: relative;
}
#foo, #ac, #dummy {
font-family: Sans-serif;
font-size: 16px;
}
#foo, #ac {
position: absolute;
top: 0;
left: 0;
}
#foo {
border: solid 1px black;
z-index: 2;
position: absolute;
top: 0;
left: 0;
background: transparent;
}
#ac {
color: #999;
top: 1px;
left: 2px;
z-index: 1;
}
#dummy {
visibility: hidden;
display: inline-block;
}
JavaScript
var values = ["hello", "dude", "rubber", "ducky"];
//dummy function to demonstrate
//returns the rest of the word being typed or null if no match
function dummyAutoComplete(inputStr) {
var i;
if(inputStr) {
for (i = 0; i < values.length; i += 1) {
if (values[i].substr(0, inputStr.length) == inputStr) {
if (values[i].length > inputStr.length) {
return values[i].substr(inputStr.length);
}
}
}
}
return null;
}
$('#foo').keyup(function(event) {
//get autocomplete value
var autoComplete = dummyAutoComplete($(this).val());
//if a value is found, show it in #ac and adjust position
if (autoComplete !== null) {
//add in value and make visible
$('#ac').html(autoComplete).removeClass('hidden');
//dummy gets the same value as the input, to measure its width
$('#dummy').html($(this).val());
//add autocomplete text-indent based on dummy width + some adjustment
$('#ac').css('text-indent', $('#dummy').outerWidth() + 'px');
} else {
//hide autocomplete
$('#ac').html('').addClass('hidden');
}
});