I am totally new to AJAX and history.js. I want to make a basic site that uses AJAX to change the content area when a nav item is clicked, preserve back button functionality as well as allow the user to type in the direct URL, such as mysite.com/page2, and have it load page2 in the content area.
I have no idea what I'm doing but history.js (as seen here) looks like what I need. In testing it out, I have no idea where to go from here. Any help is greatly apprecieted!
--Edited jQuery script
<html>
<head>
<title>test page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<!-- jQuery ScrollTo Plugin -->
<script defer src="http://balupton.github.com/jquery-scrollto/scripts/jquery.scrollto.min.js"></script>
<!-- History.js -->
<script defer src="http://balupton.github.com/history.js/scripts/bundled/html4+html5/jquery.history.js"></script>
<!-- This Gist -->
<script defer src="http://gist.github.com/raw/854622/ajaxify-html5.js"></script>
<script type="text/javascript">
$(window).bind("statechange", function(e) {
var State = window.History.getState();
if (window.console && window.console.log) {
console.log("popstate", State, window.location.href);
}
$("#changehere").text(typeof State.data.changehere !== 'undefined' ? State.data.changehere : State.url);
$('.nav').click(function() {
alert(this);
window.History.pushState({changehere:this}, this + 'title', '?' + this);
})
})
</script>
<style type="text/css">
#one {
height: 300px;
width: 1000px;
background: #a0a0a0;
}
</style>
</head>
<body>
<div id="one">
<a href="xml/first.html" id="first">change1</a>
<a href="xml/second.html" id="second">change2</a>
<a href="xml/third.html" id="third">change3</a>
</div>
<div id="changehere">
start
</div>
</body>
You need to intercept all clicks on relative links and call a History.pushState for each click. See https://github.com/browserstate/ajaxify.
The relevant part is:
$.fn.ajaxify = function(){
// Prepare
var $this = $(this);
// Ajaxify
$this.find('a:internal:not(.no-ajaxy)').click(function(event){
// Prepare
var
$this = $(this),
url = $this.attr('href'),
title = $this.attr('title')||null;
// Continue as normal for cmd clicks etc
if ( event.which == 2 || event.metaKey ) { return true; }
// Ajaxify this link
History.pushState(null,title,url);
event.preventDefault();
return false;
});
// Chain
return $this;
};