Skip to content

Instantly share code, notes, and snippets.

@ahgood
Created April 20, 2016 02:32
Show Gist options
  • Save ahgood/476618752454a77ee83d886cf5ac6eec to your computer and use it in GitHub Desktop.
Save ahgood/476618752454a77ee83d886cf5ac6eec to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Single Page Navigation with jQuery</title>
</head>
<body>
<ul id="nav">
<li>
<a href="page1">Page 1</a>
</li>
<li>
<a href="page2">Page 2</a>
</li>
</ul>
<div id="main">
<h1 id="title"></h1>
<div id="content"></div>
</div>
<script src="jquery-1.11.3.min.js"></script>
<script>
var currentUri;
var historyState = {};
var pageContent = {
'default': {
title: 'Hello',
content: 'Hello World'
},
'page1': {
title: 'Page 1',
content: 'Hello Page 1'
},
'page2': {
title: 'Page 2',
content: 'Hello Page 2'
}
};
function getCurrentUri() {
return document.URL.split(location.host + '/')[1];
}
function updateContent(uri) {
var currentContent = pageContent[uri];
if (typeof(currentContent) == 'undefined') {
currentContent = pageContent['default'];
}
jQuery('#main').fadeOut(300, function() {
jQuery('#title').html(currentContent.title);
jQuery('#content').html(currentContent.content);
jQuery('#main').fadeIn();
});
}
function route(uri) {
currentUri = getCurrentUri();
if (uri != currentUri) {
history.pushState(historyState, '', uri);
updateContent(uri);
}
return false;
}
window.onpopstate = function(event) {
currentUri = getCurrentUri();
updateContent(currentUri);
};
jQuery(function() {
currentUri = getCurrentUri();
updateContent(currentUri);
jQuery('#nav > li > a').each(function() {
jQuery(this).on('click', function(event) {
event.preventDefault();
route(jQuery(this).attr('href'));
});
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment