Skip to content

Instantly share code, notes, and snippets.

@dutchcelt
Last active February 11, 2024 20:35
Show Gist options
  • Save dutchcelt/06e17912d9ad6d1bd9e9d10238b08af0 to your computer and use it in GitHub Desktop.
Save dutchcelt/06e17912d9ad6d1bd9e9d10238b08af0 to your computer and use it in GitHub Desktop.
Restore a scroll position after a content change
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