Last active
June 3, 2017 14:53
-
-
Save apostolos/d1a3753a0e2a39579021ab227c3ed90a to your computer and use it in GitHub Desktop.
This file contains 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
// 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