Skip to content

Instantly share code, notes, and snippets.

@7cc
Created January 8, 2014 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save 7cc/8326995 to your computer and use it in GitHub Desktop.
Save 7cc/8326995 to your computer and use it in GitHub Desktop.
history ongo, onback

bug: firefox

history.state dissapears in FF

var hash = "#foo"

  1. pushState(1, null, hash)
  2. click internal link <a href="foo">
  3. hisotory.state losts in FF
history.pushState(1, null, "#section1")
console.log(history.state)
document.querySelector("a[href='#section1']").click()
// semehow you need to wait
setTimeout(function(){
  console.log(history.state)
}, 100)
// v1
var last = 0
history.replaceState(last++, null, location.href)
document.addEventListener("click", countUp)
function countUp(e) {
if( e.target.hostname && e.target.href ){
e.preventDefault()
var url = e.target.href
, c = last++
history.pushState(c, null, url)
location.replace(url)
history.replaceState(c, null, url)
}
}
window.addEventListener("popstate", isBackForward)
function isBackForward(e) {
var now = e.state
if(now > last) {
window.dispatchEvent( new Event("onGo") )
}else{
window.dispatchEvent( new Event("onBack") )
}
last = now
}
window.addEventListener("onGo", onGo)
window.addEventListener("onBack", onBack)
function onGo(){ console.log("forward") }
function onBack(){ console.log("back") }
// v3
var last = 1
history.replaceState(last++, null, location.href)
document.addEventListener("click", countUp)
function countUp(e) {
if( e.target.hostname && e.target.href ){
e.preventDefault()
var url = e.target.href
location.href = url
history.replaceState(last++, null, url)
}
}
window.addEventListener("popstate", isBackForward)
function isBackForward(e) {
var now = e.state
if(!now){
history.replaceState(last-1, null, url)
}
console.log(last, now)
if(now > last) {
window.dispatchEvent( new Event("onGo") )
}else{
window.dispatchEvent( new Event("onBack") )
}
last = now
}
window.addEventListener("onGo", onGo)
window.addEventListener("onBack", onBack)
function onGo(){ console.log("forward") }
function onBack(){ console.log("back") }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment