This block of code demonstrates how to manipulate the scrollTop property of a div element using the .getBoundingClientRect() method.
$(function () {
var liPosition = 0;
var items = $("#ulSearch li");
var divSearchContent = $("#divSearchContent");
divSearchContent.hide();
$("#txtSearch").keydown(function (e) {
if (e.keyCode == 13) { // check for enter key press
$("#txtSearch").val(items.eq(liPosition).text());
divSearchContent.hide();
return;
}
if (e.keyCode != 38 && e.keyCode != 40) { // check for up and down arrow keys
return;
}
divSearchContent.show();
items.eq(liPosition).css("background-color", "");
if (e.keyCode == 40 && liPosition < items.length - 1) { // handle down arrow key
liPosition++;
}
if (e.keyCode == 38 && liPosition > 0) { // handle up arrow key
liPosition--;
}
items.eq(liPosition).css("background-color", "red");
var b1 = divSearchContent[0].getBoundingClientRect();
var b2 = items.eq(liPosition)[0].getBoundingClientRect();
if (b1.top > b2.top) {
divSearchContent.scrollTop(divSearchContent.scrollTop() - b1.top + b2.top);
}
else if (b1.bottom < b2.bottom) {
divSearchContent.scrollTop(divSearchContent.scrollTop() - b1.bottom + b2.bottom);
}
});
});
JSFiddle