#Persist scroll position
4 messages · Page 1 of 1 (latest)
Hi @kind flame. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Astro does not natively support scroll position persistence during view transitions. However, you can implement this functionality manually using JavaScript and the Astro View Transitions API.
Here's an example of how you can do this:
<script>
import { TRANSITION_AFTER_SWAP, TRANSITION_BEFORE_PREPARATION, isTransitionBeforePreparationEvent } from 'astro:transitions/client';
const listScrollKey = `photo-gallery-scrollX`;
let direction = '';
document.addEventListener(TRANSITION_BEFORE_PREPARATION, (event: Event) => {
const list = document.querySelector('.photo-list');
if (isTransitionBeforePreparationEvent(event)) {
direction = event.direction;
}
if (list && direction === 'forward') {
sessionStorage.setItem(listScrollKey, list.scrollLeft.toString());
}
});
document.addEventListener(TRANSITION_AFTER_SWAP, () => {
const list = document.querySelector('.photo-list');
if (list && direction === 'back') {
const storedPos = Number(sessionStorage.getItem(listScrollKey));
list.scrollLeft = storedPos;
}
});
</script>
In this example, the scroll position of an element with the class .photo-list is stored in the session storage before the page transition and restored after the transition.
Please note that this is a workaround and may not work in all cases. For more complex scenarios, you might need to implement a more advanced solution.
For more information, you can refer to the Astro View Transitions Guide (https://docs.astro.build/en/guides/view-transitions/#maintaining-state) and the Astro Discord community (https://discord.com/channels/830184174198718474/1149329328434319442) for further discussions and solutions.
Sources:
- Discord support thread: Advanced scroll position storage w/ or w/o View Transitions > Answers Part 2 (https://discord.com/channels/830184174198718474/1149329328434319442)
- Astro 2.10: Persistent State in View Transitions (https://astro.build/blog/astro-2100#persistent-ui-in-view-transitions)