Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I scroll an overflowed div to a certain hashtag (anchor)?

On my webpage I have an overflowed div (i.e. with the vertical scrollbar). Inside the div, I have anchors with ids. When I put one of these ids in the URL (mypage.html#id), I want the div, not the page, to scroll to that anchor.

How do I do that, preferably with plain JavaScript? If it's too complex, I'll go with jQuery, but I'm not using it in this project for anything else.

like image 749
user323094 Avatar asked Sep 22 '11 10:09

user323094


People also ask

How do I scroll to anchor tag?

The easiest way to to make the browser to scroll the page to a given anchor is to add *{scroll-behavior: smooth;} in your style. css file and in your HTML navigation use #NameOfTheSection .

How do I scroll through a div?

To fit all the text inside the div, the single-direction scrolling method will be used. You can apply it by placing the overflow-y:scroll in the id growth inside the style tag. Notice the scroll bar on the right side of the div .


2 Answers

For those of you in nearly any major browser in 2021, use element.scrollIntoView().

https://developer.mozilla.org/docs/Web/API/Element/scrollIntoView

The Element interface's scrollIntoView() method scrolls the element's parent container such that the element on which scrollIntoView() is called is visible to the user - MDN Web Docs

Example:

var myEl = document.getElementById("child");
myEl.scrollIntoView()

or with Parameters -- Not supported in Safari or Internet Explorer:

myEl.scrollIntoView({
    block: "center" // Start, center, end, or nearest. Defaults to start.
    behavior: "smooth"
})
like image 68
itsisaac19 Avatar answered Nov 15 '22 16:11

itsisaac19


This is a pure Javascript (ECMA 6) solution, similar to Ariel's answer.

const overflow = document.querySelector('.overflow');
const anchor = document.getElementById('anchor');

// Get the bounding client rectangles for both
// the overflow container and the target anchor
const rectOverflow = overflow.getBoundingClientRect();
const rectAnchor = anchor.getBoundingClientRect();

// Set the scroll position of the overflow container
overflow.scrollTop = rectAnchor.top - rectOverflow.top;
like image 38
Caleb Avatar answered Nov 15 '22 16:11

Caleb