How Do I Scroll An Overflowed Div To A Certain Hashtag (anchor)?
Solution 1:
$('.overflow').scrollTop($('#anchor').offset().top);
There is no reason at all you can't convert this to standard javascript.
Note that the scroll will be off if there is a margin on the anchor element.
Solution 2:
Have you tried to set focus()
on the anchor?
Any DOM element with a tabindex is focusable, and any element which has focus will be scrolled into view by the browser.
Solution 3:
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;
Solution 4:
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"
})
Post a Comment for "How Do I Scroll An Overflowed Div To A Certain Hashtag (anchor)?"