Scroll an Element Into View with Vanilla JavaScript
A click on the HTML element with the ID myButton
will trigger a smooth scroll to the element with the ID myDestination
using the JavaScript function Element: scrollIntoView()
:
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('#myButton').addEventListener('click', function (event) {
event.preventDefault();
this.blur();
const myDestination = document.querySelector('#myDestination');
myDestination.scrollIntoView({'behavior': 'smooth'});
});
});
If the site has a fixed header, scrollIntoView()
will not work exactly as intended. It doesn't account for the header. Get the Y coordinate of the top of the object to scroll into view using offsetTop
and subtract the height of the fixed header element from that. Scroll the window to the Y position, rather than the element directly:
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('#myButton').addEventListener('click', function (event) {
event.preventDefault();
this.blur();
const myDestination = document.querySelector('#myDestination');
const fixedHeaderHeight = 120; // height of fixed header
const topOfMyDestination = myDestination.offsetTop - fixedHeaderHeight;
window.scroll({ top: topOfMyDestination, behavior: "smooth" });
});
});
Feedback?
Email us at enquiries@kinsa.cc.