I have an element that opens via Ajax to take the place of a generic "select" menu. And if the user has already selected something in advance then, when they click to open it, I want to automatically scroll down to that selected position.
I've been doing it like this, but the position is off by about 15px; it should be at 246, but instead it's at 231:
// assume they pre-selected option_3
<div id="select">
<div id="option_1">Blah</div>
<div id="option_2">Blah</div>
<div id="option_3">Blah</div>
</div>
$('#select').scrollTop($('#option_3').position().top);
</script>
The best way I can think to do this is to find parent container's offset().top, then find the selected item's offset().top... subtract one from the other, and then use scrollTop to drop down to that location. But that's a lot of math for what SHOULD be simple:
<script>
var starter = $('#select').offset().top;
var ender = $('#option_3').offset().top;
var offset = ender - starter;
$('#select').scrollTop(offset);
</script>
Or, of course, I can just add 15 to the position, but that seems like a work-around that might not be right for every browser instead of the "right" way to do it:
$('#select').scrollTop($('#option_3').position().top + 15);
What do you guys think? Any guess as to why position().top is off by 15px?