Skip to content

Instantly share code, notes, and snippets.

@andreasvirkus
Created May 5, 2016 16:58
Show Gist options
  • Save andreasvirkus/8cb2356084a232a90f02ab9281629841 to your computer and use it in GitHub Desktop.
Save andreasvirkus/8cb2356084a232a90f02ab9281629841 to your computer and use it in GitHub Desktop.
/**
* A simple drop-in snippet to ajaxify a site.
* If the user's browser doesn't support HTML5 History API,
* the site will navigate regularly.
*
* Change content and menu link selectors according to your need.
*
* Dependencies: jQuery 2+, jQuery.history
*/
(function(window, jQuery){
if(!Modernizr.history){
console.log("No HTML5 pushState support!");
}
var content = '#content', // Selector to load
$content = $(content),
state = History.getState(),
$menuLink = $('#primary-menu a');
$menuLink.on('click', function (e) {
e.preventDefault();
var $this = $(this),
href = $this.attr('href');
$this.parent().addClass('current_page_item').siblings()
.removeClass('current_page_item');
History.pushState(null, document.title, href); // change the url and add our ajax request to our history
});
// Browser's native back button
$(window).on('statechange', function(){
state = History.getState(); // Find out what we previously ajaxed in
$content.addClass('loading-content');
// TODO: use events instead of arbitrary timeouts
setTimeout(function () {
$content.load(state.url + ' #primary');
}, 200);
setTimeout(function () {
$content.removeClass('loading-content');
}, 400);
// Old load block
// $content.animate({
// opacity: 0
// }, 250, function () {
// $(this).load(state.url + ' #primary', function () {
// $(this).animate({
// opacity: 1
// }, 200);
// });
// });
});
}(window, $));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment