Skip to content

Instantly share code, notes, and snippets.

@boye
Created August 2, 2014 11:18
Show Gist options
  • Save boye/eec3cf9d037df84a7965 to your computer and use it in GitHub Desktop.
Save boye/eec3cf9d037df84a7965 to your computer and use it in GitHub Desktop.
Custom statechange event that will be triggered after manually calling history.pushState
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Custom statechange event</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="padding:1em;">
<h1>Custom <code>statechange</code> event</h1>
<p>
<a href="#foo" onclick="history.pushState({foo:'bar'}, '', '#foo'); return false;">Go to #foo</a>
<a href="#bar" onclick="history.pushState(null, '', '#bar'); return false;">Go to #bar</a>
<a href="/">Back to index</a>
</p>
<script>
(function (window) {
'use strict';
var root = window,
document = root.document,
location = document.location,
evt = document.createEvent('Event');
evt.initEvent('statechange', true, true);
function listen() {
var uri = location.href,
check = function () {
if ( uri !== location.href ) {
clearInterval(timer);
// Pass along the history state data
evt.state = history.state;
// Start listening again after dispatching event
if ( window.dispatchEvent(evt) ) {
listen();
}
}
},
timer = setInterval(check, 500);
}
listen();
}(this));
// Listen for the event
window.addEventListener('statechange', function (e) {
console.log('statechange', e.state);
}, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment