Last active
May 22, 2023 08:44
-
-
Save crongro/e8cfd75555b5fb776ecef63032be35ae to your computer and use it in GitHub Desktop.
history API Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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