I have a scrolling division which contains a list of hotels, grouped alphabetically. Above this division, I have an alphabetical index of links, which when clicked, I would like the corresponding alphabetical item to scroll upwards, within the division.
I've spent about an hour scouring the web and trying various techniques, and haven't found anything that does what I'm looking for, or at least something I can understand; I'm no jQuery genius.
Any assistance would be much appreciated!
What you want is element.scrollIntoView();
this will scroll the browser window/div to make an element visible on the page.
An example of this: fiddle link
Update: Added a more complete dynamic example.
CSS
#container {
overflow: auto;
height: 50px;
}
.scrollto {
color: blue;
text-decoration: underline;
cursor: pointer;
}
HTML
<span class="scrollto">a</span> <span class="scrollto">e</span> <span class="scrollto">i</span>
<div id='container'>
<div id="a">a</div>
<div id="b">b</div>
<div id="c">c</div>
<div id="d">d</div>
<div id="e">e</div>
<div id="f">f</div>
<div id="g">g</div>
<div id="h">h</div>
<div id="i">i</div>
</div>
JS
$('.scrollto').click(function() {
$('#' + $(this).text()).get(0).scrollIntoView();
// or $('#' + $(this).text())[0].scrollIntoView();
});
Basically in this example I created a small overflowed div causing it to have a scrollbar.
I then use id
anchors on div tags inside of it to label the different areas in it. I have a span outside the div to auto scroll to a certain anchor point inside the overflowed div when clicked.
@Wayne Smallman: As per the html code in your comment, this is what you would use
$('div#index ul li a').click(function() {
$($(this).attr('href')).get(0).scrollIntoView();
});
Fiddle Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With