HTML onpopstate Event Attribute
Description
The HTML onpopstate
event attribute is triggered when the history of the window changes. This can happen when the user clicks the back or forward buttons, or when the developer uses the history.pushState()
or history.replaceState()
methods to update the history stack.
The onpopstate
event is a good way to keep track of the user's navigation history and update the page accordingly. For example, you could use it to highlight the current page in a navigation bar, or to load different content depending on the user's previous page.
To use the onpopstate
event attribute, you would add it to the <body>
element of your HTML document. The value of the attribute should be a JavaScript function that will be called when the event is triggered.
Here is an example of how to use the onpopstate
event attribute:
<body onpopstate="myFunction()">
...
</body>
function myFunction() {
// Update the page based on the user's navigation history
}
The onpopstate
event object contains a number of properties that can be used to get information about the current history entry. These properties include:
state
: An object containing any data that was passed to thehistory.pushState()
orhistory.replaceState()
methods.type
: The type of history navigation that occurred. This can be"push"
,"replace"
, or"pop"
.hash
: The hash fragment of the current URL.
Syntax
<element onpopstate="script">
Values
- scriptThe name of the script to use when the event has been triggered.
Example
<!DOCTYPE html>
<html>
<body>
<p>Reload page to trigger event</p>
<script>
window.onpopstate = function(event) {
alert("EXAMPLE: location: " + document.location +
", state: " + JSON.stringify(event.state));
};
history.pushState({
page: 1
}, "title 1", "?page=1");
history.pushState({
page: 2
}, "title 2", "?page=2");
history.replaceState({
page: 3
}, "title 3", "?page=3");
// alerts "location:
// https://www.cssportal.com/html-event-attributes/onpopstate.php?page=1,
// state: {"page":1}"
history.back();
// alerts "location: about:blank, state: null"
history.back();
</script>
</body>
</html>
Browser Support
The following table will show you the current browser support for the HTML onpopstate
Event Attribute.
Desktop | |||||
Yes | Yes | Yes | Yes | Yes |
Tablets / Mobile | |||||
Yes | Yes | Yes | Yes | Yes | Yes |
Last updated by CSSPortal on: 14th October 2023