Skip to content

Instantly share code, notes, and snippets.

@apostolos
Last active June 3, 2017 14:53
Show Gist options
  • Save apostolos/d1a3753a0e2a39579021ab227c3ed90a to your computer and use it in GitHub Desktop.
Save apostolos/d1a3753a0e2a39579021ab227c3ed90a to your computer and use it in GitHub Desktop.
// Let's say we want to scroll to #my-target
flipScroll('my-target');
const flipScroll = (trg) => {
const trgEl = document.getElementById(trg);
// Store current scroll
const prevScroll = getScrollTop();
// Perform the scroll
if (trgEl.scrollIntoViewIfNeeded) {
trgEl.scrollIntoViewIfNeeded();
} else if (trgEl.scrollIntoView) {
trgEl.scrollIntoView();
} else {
window.scroll(0, trgEl.getBoundingClientRect().top + window.pageYOffset - 100);
}
// Compute scroll offset
const scrollOffset = getScrollTop() - prevScroll;
// Apply FLIP transform
document.body.style.transform = `translate3d(0, ${scrollOffset}px, 0)`;
// Apply class that transitions transform back to zero
document.body.classList.add('flip-translate');
}
// Helper function that returns vertical scroll
const getScrollTop = () => {
const doc = document.documentElement;
return (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment