Skip to content

Instantly share code, notes, and snippets.

@laserpez
Last active August 29, 2015 14:08
Show Gist options
  • Save laserpez/be7523b5990d6d3be6ba to your computer and use it in GitHub Desktop.
Save laserpez/be7523b5990d6d3be6ba to your computer and use it in GitHub Desktop.
history pushState/onpopstate example
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<title>History</title>
<body>
<button id='btn'>Click</button>
<span id='txt'></span>
</body>
</html>
<script type="text/javascript">
times = 0
$(document).ready(function() {
$('#txt').text('counter = ' + times)
history.pushState({'counter': times}, null)
$('#btn').click(function() {
times += 1
state = {'counter': times}
console.log('saving ' + state['counter'])
history.pushState(state, null)
$('#txt').text('counter = ' + times)
})
});
window.onpopstate = function(event) {
console.log(event.state)
if (event.state == null) return;
times = event.state['counter']
$('#txt').text('counter = ' + times)
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment