I have a website that serves content like so, using .js:
var FluidNav = {
init: function() {
$("a[href*=#]").click(function(e) {
e.preventDefault();
if($(this).attr("href").split("#")[1]) {
FluidNav.goTo($(this).attr("href").split("#")[1]);
}
});
this.goTo("home");
},
goTo: function(page) {
var next_page = $("#"+page);
var nav_item = $('nav ul li a[href=#'+page+']');
$("nav ul li").removeClass("current");
nav_item.parent().addClass("current");
FluidNav.resizePage((next_page.height() + 40), true, function() {
$(".page").removeClass("current"); next_page.addClass("current");
});
$(".page").fadeOut(500);
next_page.fadeIn(500);
FluidNav.centerArrow(nav_item);
},
centerArrow: function(nav_item, animate) {
var left_margin = (nav_item.parent().position().left + nav_item.parent().width()) + 24 - (nav_item.parent().width() / 2);
if(animate != false) {
$("nav .arrow").animate({
left: left_margin - 8
}, 500, function() { $(this).show(); });
} else {
$("nav .arrow").css({ left: left_margin - 8 });
}
},
resizePage: function(size, animate, callback) {
if(size) { var new_size = size; } else { var new_size = $(".page.current").height() + 40; }
if(!callback) { callback = function(){}; }
if(animate) {
$("#pages").animate({ height: new_size }, 400, function() { callback.call(); });
} else {
$("#pages").css({ height: new_size });
}
}};
So far so good, but the client wants a browser back button functionality integrated. I did my homework and with the help of SO and other sources found out that the pushState and popState are the best way to achieve this.
If you take a second to read the code above, you will find out the following:
- If you type website.com/#team in your browser, you are going to get the front page, not the #team page. If you want to navigate to #team, you are going to have to click from there.
- If you navigate to #team and then want to go back to the front page, and you press the back button, you are going to get redirected to where you were before vising the website. Kicked out so to speak.
This is done with the purpose of a smoother browsing experience.
However, I now need to achieve the following, and I am a bit lost as to what changes I am going to have to make to my .js file above:
- Achieve a working back-button functionality (manipulate the browser's history storage)
- When I type website.com/#team in the URL bar, to go to that page and not the front page.
Here is an example website built with this functionality so you can see how it functions. http://themes.two2twelve.com/site/fluidapp/light/