Skip to content

Instantly share code, notes, and snippets.

@veryrobert
Last active January 4, 2016 05:49
Show Gist options
  • Save veryrobert/8577726 to your computer and use it in GitHub Desktop.
Save veryrobert/8577726 to your computer and use it in GitHub Desktop.
Ajax function with working back button
$(document).ready(function(){
ajaxCall('nav a', '#container', '#guts', 200);
});
var ajaxCall = function(link, container, guts, speed){
var mainContent = $(container);
var contents = $(guts);
var makeCall = $(link);
var checkBack = function() {
$(window).on('popstate', function(){
_link = location.pathname.replace(/^.*[\\\/]/, ''); //get filename only
loadContent(_link);
});
}
makeCall.on("click", function(e) {
_link = $(this).attr("href");
history.pushState(null, null, _link);
loadContent(_link);
e.preventDefault();
});
function loadContent(href){
mainContent.find(guts).fadeOut(speed, function() {
mainContent.hide().load(href + " " + guts, function() {
mainContent.fadeIn(speed, function() {
});
});
});
checkBack();
}
};
<!Doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax Call</title>
</head>
<body>
<nav>
<ul>
<li><a href="work.html">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</nav>
<div id="container">
<div id="guts">
<!-- Place content here -->
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment