Skip to content

Instantly share code, notes, and snippets.

@Hemalatah
Forked from anandnalya/app_1.js
Created August 8, 2016 21:01
Show Gist options
  • Save Hemalatah/9caf11836b87e9f986ce028c9a21b5c0 to your computer and use it in GitHub Desktop.
Save Hemalatah/9caf11836b87e9f986ce028c9a21b5c0 to your computer and use it in GitHub Desktop.
Building a Single Page Webapp with jQuery
$(document).ready(function() {
// convert all a/href to a#href
$("body").delegate("a", "click", function(){
var href = $(this).attr("href"); // modify the selector here to change the scope of intercpetion
// Push this URL "state" onto the history hash.
$.bbq.pushState(href,2);
// Prevent the default click behavior.
return false;
});
});
$(document).ready(function() {
// Bind a callback that executes when document.location.hash changes.
$(window).bind( "hashchange", function(e) {
var url = Object.extended($.bbq.getState()).keys();
if(url.length==1){
url = url[0];
}else{
return;
}
// url action mapping
if(url.has(/^\/users$/)){
showUserList();
} else if (url.has(/^\/users\/\d+$/)){ // matching /users/1234
showUser(url)
}
// add more routes
});
});
$(document).ready(function() {
if(window.location.hash==''){
window.location.hash="#/users"; // home page, show the default view (user list)
}else{
$(window).trigger( "hashchange" ); // user refreshed the browser, fire the appropriate function
}
});
var showUserList = function(){
$('#app').load('/html/users.html #userListDiv', function() {
$.getJSON('/users', function(data) {
// create the user list
var items = [ '<ul>'];
$.each(data, function(index, item) {
items.push('<li><a href="/users/"' + item.id + '">'
+ item.name + '</a></li>');
});
items.push('</ul>');
var result = items.join('');
// clear current user list
$('#userListDiv').html('');
// add new user list
$(result).appendTo('#userListDiv');
});
}
};
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript" src="./scripts/sugar.js"></script>
<script type="text/javascript" src="./scripts/jquery-1.7.js"></script>
<script type="text/javascript" src="./scripts/app.js"></script>
</head>
<body>
<div id="doc">
<div id="hd">
Header/Navigation goes here
</div>
<div id="mainContent" class="content">
<div id="app" role="application">
This is the content area
</div>
</div>
<div id="ft">
Footer goes here
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment