Skip to content

Instantly share code, notes, and snippets.

@59naga
Created October 13, 2013 05:22
Show Gist options
  • Save 59naga/6958463 to your computer and use it in GitHub Desktop.
Save 59naga/6958463 to your computer and use it in GitHub Desktop.
window.addEventListener('popstate',function(){console.log(location.search)});
history.pushState(null,null,'?page=2');
<meta charset="UTF-8">
<script>
window.addEventListener('load',main,false);
function main(){
var _title=document.title;
var buttons=document.querySelectorAll('button');
Array.prototype.forEach.call(buttons,function(button){
button.onclick=function(){
var query=Query.create(location.search);
query.button=this.innerText;
history.pushState(null,null,query.toString());
window.dispatchEvent(document.createEvent('PopStateEvent'));
}
});
window.addEventListener('popstate',function(event){
var title=_title;
var query=Query.create(location.search);
if(query.hasOwnProperty('button')){
title=query.button;
}
switch(query.button){
case 'hoge':
document.querySelector('pre').innerText=1;
break;
case 'fuga':
document.querySelector('pre').innerText=2;
break;
case 'piyo':
document.querySelector('pre').innerText=3;
break;
default:
document.querySelector('pre').innerText=0;
break;
}
document.title=title;//pushStateに適用される
},false);
}
Query.create=function(search){return new Query(search)}
function Query(search){
var self=this;
Object.call(self);
var search=search? search.substr(1): "";
if(search){
search.split('&').forEach(function(param){
var param=param.split('=');
var key=decodeURIComponent(param[0]);
var value=param[1];
if(value){
value=decodeURIComponent(param[1]);
}
self[key]=value;
});
}
}
Query.prototype.toString=function(){
var params=[];
for(var key in this){
if(this.hasOwnProperty(key)){
var param=encodeURIComponent(key);
if(this[key]){
param+='='+encodeURIComponent(this[key]);
}
params.push(param);
}
}
return params.length? "?"+params.join('&'): "";
}
</script>
<body>
<button>hoge</button>
<button>fuga</button>
<button>piyo</button>
<pre></pre>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment