Let's say I have two pages, current.html and previous.html, and I navigated to current.html from previous.html.
So my browser currently is displaying current.html as the url, and if I look at the tab history, previous.html is displayed as the previous entry.
I want to play a CSS animation on previous.html when the user clicks the back from current.html (or forward, but I can't even figure out back yet lol) button in their browser.
I am at a loss as to how to do this. My initial thought was using the popstate event. However, this requires me to push an the previous url manually again into the browser history, since popstate only fires when you manually add/replace history entries with push and replacestate (I think?).
The best I could come up with right now is doing a pushstate which sets the url to previous.html, and doing history.back, but the order here is the opposite of what I want.
Is there any way I could feasibly do this?
Thanks!
In the previous.html
page, add a JavaScript code block to listen for the pageshow
event:
window.addEventListener('pageshow', function(event) {
if (event.persisted || (window.performance && window.performance.navigation.type === 2)) {
// Play your CSS animation here
console.log('Animation played on previous.html');
}
});
In the current.html
page, when the user clicks the back button, you can use the history.replaceState()
method to update the state of the previous.html
page and trigger the pageshow
event:
window.addEventListener('popstate', function(event) {
history.replaceState({}, document.title, window.location.href);
});
Note: You might need to add additional logic to differentiate between the initial load and the back navigation if needed, because the pageshow
event will also be triggered on the initial load of the previous.html
page.