Skip to content

Instantly share code, notes, and snippets.

@crongro
Last active May 22, 2023 08:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save crongro/e8cfd75555b5fb776ecef63032be35ae to your computer and use it in GitHub Desktop.
Save crongro/e8cfd75555b5fb776ecef63032be35ae to your computer and use it in GitHub Desktop.
history API Example
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Untitled</title>
<style>
h1 {
color: red;
}
.view {
background-color: #fff;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<h1>hello world</h1>
<div class="view"> </div>
<button>Change</button>
<script>
const getRandomColor = () => {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r},${g},${b})`;
};
document.querySelector("button").addEventListener("click", (e) => {
const color = getRandomColor();
document.querySelector(".view").style.backgroundColor = color;
history.pushState({
color: color
}, "title 1", `?color=${color}`);
document.title = color;
});
window.addEventListener("popstate", (event) => {
console.log('popstate fired !');
const style = document.querySelector(".view").style;
if (event.state && event.state.color) {
style.backgroundColor = event.state.color;
} else {
style.backgroundColor = "#fff";
}
});
//history.replaceState({page: 3}, "title 3", "?page=3")
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment