Scrolling to an anchor inside a DIV when externally clicked, via jQuery

I have a scrolling unit that contains a list of hotels grouped alphabetically. Above this division, I have an alphabetical index of links that, when pressed, I would like the corresponding alphabetical element to scroll upward, within the division.

I spent about an hour cleaning the network and trying various methods, and did not find anything that does what I am looking for, or at least something that I can understand; I am not a jQuery genius.

Any help would be greatly appreciated!

+4
source share
1 answer

What you want is element.scrollIntoView(); , this will scroll the browser window / div to make the element visible on the page.

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 crowded div, making it have a scroll bar.

Then I use the id bindings in the div tags inside it to mark different areas in it. I have a gap out of the way to automatically scroll to a specific anchor point inside an overflowing DIV when clicked.


@Wayne Smallman . According to the HTML in your comment, this is what you would use

 $('div#index ul li a').click(function() { $($(this).attr('href')).get(0).scrollIntoView(); }); 

Demo Screenshot

+16
source

Source: https://habr.com/ru/post/1381577/


All Articles