As I work on a small website that features multiple pages with similar layouts, I often find that only the content within a specific div varies. The rest of the elements such as navigation and header remain consistent throughout.
To address this, I have set up a "base" HTML file along with smaller HTML files containing only the content-div and incorporated JavaScript code like the following (to be activated upon clicking a button):
$.get("content/text1.html", function(data) {
$("#content").html(data);
});
This process works seamlessly; however, it presents an issue where the URL in the address bar does not change with these requests. This makes it challenging for users to directly link to particular pages. While I am aware of using #-urls as a workaround, my preference is to utilize URLs like:
example.com/talks/foo/bar
And avoid any workarounds.
In a separate discussion thread, someone directed me towards the HTML5 browser history API, particularly history.js.
My objective with this integration is twofold:
- Upon clicking a button, trigger an AJAX request to update the content of the content-div and concurrently update the URL to something akin to
example.com/talks/foo/bar
- If a user manually types in
example.com/talks/foo/bar
into their browser, replicate the same AJAX request and content update as described in (1)
I attempted to achieve the first goal through:
$.get("content/text1.html", function(data) {
$("#content").html(data);
History.pushState(null, null, "content/text1.html");
});
However, I am uncertain about how to effectively tackle the second point. Should I consider implementing a rewriterule that redirects all traffic to the base HTML file, accompanied by JavaScript logic to decipher the URL and prompt the AJAX request?
I sense that my current approach may require adjustment..
Is this the correct usage of history.js?
How can I successfully implement the second bullet point?