I upload my content to my website in a div called #container with jQuery / Ajax. I have different types of links:
- normal anchor links
- JQuery-Triggers that trigger an event when a specific div is clicked.
Now I want to add functionality to support back and forward browser buttons and bookmark functionality. I came across history.js, but I have a few problems with it and cannot find a really simple tutorial on how to use it correctly.
My links:
<a href='#imprint' class='link_imprint'>Imprint</a>
I read that SEO is better to use <a href="imprint/" ... but this URL will not be found on my server. So my first question is, how can I guarantee that myurl.com/imprint works and does not lead to 404 pages?
Arriving at history.js ... At the moment, I have included the following code in my index.php right after <body>
<script> $(document).ready(function(){ (function(window,undefined){ // Prepare var History = window.History; // Note: We are using a capital H instead of a lower h if ( !History.enabled ) { // History.js is disabled for this browser. // This is because we can optionally choose to support HTML4 browsers or not. return false; } // Bind to StateChange Event History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate alert("state"); var State = History.getState(); // Note: We are using History.getState() instead of event.state }); History.Adapter.bind(window,'anchorchange',function(){ }); var currentState = History.getState(); var currentUrl = currentState.url; var urlParts = currentUrl.split('#'); $('#container').load('templates/'+ urlParts[1] +'.php'); $('#footer.credits').on('click','.link_imprint',function() { var currentUrl = $(this).attr('href'); var urlParts = currentUrl.split('#'); History.pushState(null,null,currentUrl); $('#container').load('templates/'+ urlParts[1] +'.php'); }); })(window); });
Using this code, after clicking the link, the URL changes to: myurl / # imprint and imprint.php is loaded into the container.php file. But when I click the back button now, the url is changing, but the content is still one of the prints. How can I make sure the container is updated with old content? I think I forgot something, but I donβt know what I should do. I tried it with statechange / anchorstate, but none of both events will be fired when I click the back button.
Thanks for helping me.
PS: I added a warning about the state change event, but it will never be triggered. That can't be right, can it? I see how anchorchange-event fires when I click on a link and url changes myurl.com/#imprint ...