Skip to content

Instantly share code, notes, and snippets.

@mstudio
Created April 27, 2022 16:16
Show Gist options
  • Save mstudio/b8a91db438c43b8e169229d8f2a28b3c to your computer and use it in GitHub Desktop.
Save mstudio/b8a91db438c43b8e169229d8f2a28b3c to your computer and use it in GitHub Desktop.
Scroll to a particular element
/**
* Smooth scrolls to an element's position
* @param {string} buttonSelector
* @param {string} gotoSelector - element to scroll to
* @param {Number} yOffset - Y offset for scrolling
*/
export const addScrollLink = (
buttonSelector,
gotoSelector,
yOffset = 0,
) => {
setTimeout(() => {
const buttons = [...document.querySelectorAll(buttonSelector)];
buttons.forEach((button) => {
if (button) {
button.addEventListener("click", () => {
var elementPosition = document
.querySelector(gotoSelector)
.getBoundingClientRect().top;
window.scroll({
top: elementPosition + window.pageYOffset + yOffset,
behavior: "smooth",
});
});
}
});
}, 100);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment