Last active
February 11, 2024 20:35
-
-
Save dutchcelt/06e17912d9ad6d1bd9e9d10238b08af0 to your computer and use it in GitHub Desktop.
Restore a scroll position after a content change
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
import passive from './setPassiveEvent.js'; | |
// DOMMouseScroll is specific to Firefox | |
const eventTypes = ['mousewheel', 'touchmove', 'DOMMouseScroll']; | |
class ScrollPosition { | |
constructor(viewport) { | |
this.viewport = viewport || document.body; | |
this.scrollPosition = this.getScrollPosition(); | |
this.listenerMethod = 'add'; | |
} | |
handleEvent() { | |
this.scrollPosition = this.getScrollPosition(); | |
} | |
getScrollPosition() { | |
return { left: this.viewport.scrollLeft, top: this.viewport.scrollTop }; | |
} | |
setScrollPosition() { | |
scrollTo(this.scrollPosition.left, this.scrollPosition.top); | |
this.listenerMethod = 'remove'; | |
} | |
set listenerMethod(prefix) { | |
eventTypes.forEach(type => { | |
this.viewport[`${prefix}EventListener`](type, this, passive); | |
}); | |
} | |
} | |
export default function(viewport) { | |
if ('addEventListener' in window) { | |
return new ScrollPosition(viewport); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment