I am having trouble transitioning a hero video between two pages using Swup.js.
Currently I can transition the video element using a custom class called 'transition-wipe' which changes the width of the video from 50% to 100% on page change, that works fine however the video restarts when the next page is loaded.
Is there a way to pause the video when transitioning and play the next video from where the previous one left off? My intention is for the video to appear dynamic between pages and to play continuously without restarting. I can't seem to find any solutions for this so any suggestions would be greatly appreciated! :)
You could use the Web Storage API to store the position of the video in the browser. Here below are two abstractions that get and set the stored video position with localStorage
.
/**
* Returns 0 or the position of the video.
*/
const getVideoPosition = () => {
return Number(localStorage.getItem('video-position'));
}
/**
* Saves the video in the current position.
*/
const setVideoPosition = value => {
localStorage.setItem('video-position', value);
}
After each reload select the video element, get the saved position and update the currentTime
property of the video to start from that position.
const position = getVideoPosition();
video.currentTime = position;
Make your video listen to the timeupdate
event to constantly save the last position and the ended
event to reset the saved position.
video.addEventListener('timeupdate', ({ target }) => {
const { currentTime } = target;
setVideoPosition(currentTime);
});
video.addEventListener('ended', ({ target }) => {
setVideoPosition(0);
});