Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save thezacharytaylor/7485f25e9d3752aea37952239be7b768 to your computer and use it in GitHub Desktop.
Save thezacharytaylor/7485f25e9d3752aea37952239be7b768 to your computer and use it in GitHub Desktop.
JavaScript Force Scroll on Click
/**
* Scroll to top of page when lower nav link is clicked in calendar.
*/
import { ready } from '../utils/ready';
function fetchButtons() {
return document.querySelectorAll(
'.tribe-events-c-nav__list-item > a, .tribe-events-c-nav__list-item > button'
);
}
function addListeners(buttons) {
buttons.forEach((btn) => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
// Slight delay for aesthetic purposes.
setTimeout(function () {
window.scrollTo(0, 0);
}, 1000);
// Delay to set new listeners via recursion.
setTimeout(function () {
let newButtons = fetchButtons();
if (newButtons.length !== 0) {
addListeners(newButtons);
}
}, 4000);
});
});
}
ready(() => {
let eventNavButtons = fetchButtons();
if (eventNavButtons.length === 0) {
return;
} else {
addListeners(eventNavButtons);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment