Last active
December 28, 2015 09:59
-
-
Save arozwalak/7483269 to your computer and use it in GitHub Desktop.
HTML5: History API
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> | |
<head> | |
<meta charset="utf-8"> | |
<title>History API</title> | |
</head> | |
<body> | |
<ul> | |
<li><a href="img/Penguins.jpg" title="Penguin" data-url="penguin">Penguin</a></li> | |
<li><a href="img/Chrysanthemum.jpg" title="Chrysanthemum" data-url="chrysanth">Chrysanthemum</a></li> | |
<li><a href="img/Jellyfish.jpg" title="Jellyfish" data-url="jellyfish">Jellyfish</a></li> | |
</ul> | |
<div class="result"> | |
<script id="template" type="template"> | |
<h2>{{title}}</h2> | |
<img src="{{imgSrc}}" alt="{{title}}"> | |
</script> | |
</div> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script> | |
<script> | |
;(function() { | |
if (!!(window.history && history.pushState)) { | |
var Viewer = { | |
template: $('#template').html(), | |
init: function() { | |
$('ul').on('click', 'a', function(e) { | |
Viewer | |
.applyTemplate(this) | |
.updateHistory(this); | |
e.preventDefault(); | |
}); | |
this.handleState(); //listen of back or forward button | |
}, | |
applyTemplate: function(data) { | |
var template = this.template.replace(/{{title}}/g, data.title) | |
.replace(/{{imgSrc}}/g, data.href); | |
$('.result').children() | |
.remove() | |
.end() | |
.append(template); | |
return this; | |
}, | |
updateHistory: function(data) { | |
var dataToSave = { | |
title: data.title, | |
href: data.href, | |
url: data.dataset.url | |
}; | |
history.pushState( | |
dataToSave, | |
data.title, | |
data.dataset.url | |
); | |
}, | |
handleState: function() { | |
$(window).on('popstate', function(e) { | |
// console.log(e); | |
if (e.originalEvent.state) { | |
Viewer.applyTemplate(e.originalEvent.state); | |
} | |
}) | |
} | |
}; | |
Viewer.init(); | |
}; | |
})(); | |
</script> | |
<script> | |
// history.pushState( | |
// // data | |
// // title | |
// // url | |
// 'some data', | |
// 'My Page Title', // show in menu of Prewious button | |
// 'page' | |
// ); | |
// window.addEventListener('popstate', function(e) { | |
// console.log(e); | |
// }); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment