How do I scroll to an element using JavaScript?
scrollIntoView works well:
document.getElementById("divFirst").scrollIntoView();
full reference in the MDN docs:
https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView
The best, shortest answer that what works even with animation effects:
var scrollDiv = document.getElementById("myDiv").offsetTop;
window.scrollTo({ top: scrollDiv, behavior: 'smooth'});
If you have a fixed nav bar, just subtract its height from top value, so if your fixed bar height is 70px, line 2 will look like:
window.scrollTo({ top: scrollDiv-70, behavior: 'smooth'});
Explanation:
Line 1 gets the element position
Line 2 scroll to element position; behavior
property adds a smooth animated effect
You can use an anchor to "focus" the div. I.e:
<div id="myDiv"></div>
and then use the following javascript:
// the next line is required to work around a bug in WebKit (Chrome / Safari)
location.href = "#";
location.href = "#myDiv";
For Chrome and Firefox
I've been looking a bit into this and I figured this one out which somehow feels like the most natural way to do it. Of course, this is my personal favorite scroll now. :)
const y = element.getBoundingClientRect().top + window.scrollY;
window.scroll({
top: y,
behavior: 'smooth'
});
For IE, Edge and Safari supporters
Note that window.scroll({ ...options })
is not supported on IE, Edge and Safari. In that case it's most likely best to use
element.scrollIntoView()
. (Supported on IE 6). You can most likely (read: untested) pass in options without any side effects.
These can of course be wrapped in a function that behaves according to which browser is being used.