Created
April 27, 2022 16:16
-
-
Save mstudio/b8a91db438c43b8e169229d8f2a28b3c to your computer and use it in GitHub Desktop.
Scroll to a particular element
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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