Skip to content

Instantly share code, notes, and snippets.

@rileyrichter
Created June 24, 2024 21:18
Show Gist options
  • Save rileyrichter/4c5e7695fc46c5d4398caf7cd42dc39a to your computer and use it in GitHub Desktop.
Save rileyrichter/4c5e7695fc46c5d4398caf7cd42dc39a to your computer and use it in GitHub Desktop.
/*
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// Set a pixel value for the amount of
// space you want between the top of the
// page and the top of the accordion
const offset = 16;
// add the class of your accordion to
// the querySelector, we're using the native
// Webflow dropdown element here
const accordions = document.querySelectorAll(".accordion");
// Set a delay in milliseconds for the scroll
// and remember you'll want this to match any
// animations you have on your accordion in Webflow
const delay = 50;
// check if the user prefers reduced motion
const motionState = window.matchMedia("(prefers-reduced-motion: reduce)");
function scrollToElement(element) {
const elementPosition = element.getBoundingClientRect().top + window.scrollY;
const offsetPosition = elementPosition - offset;
if (motionState.matches) {
window.scrollTo({
top: offsetPosition,
});
} else {
window.scrollTo({
top: offsetPosition,
behavior: "smooth",
});
}
}
// Loop through each accordion and add an event listener
document.addEventListener("DOMContentLoaded", function () {
accordions.forEach((accordion) => {
accordion.addEventListener("click", function () {
setTimeout(() => {
scrollToElement(this);
}, delay);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment