Good tutorial for using HTML5 History API (Pushstate?)
For a great tutorial the Mozilla Developer Network page on this functionality is all you'll need: https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history
Unfortunately, the HTML5 History API is implemented differently in all the HTML5 browsers (making it inconsistent and buggy) and has no fallback for HTML4 browsers. Fortunately, History.js provides cross-compatibility for the HTML5 browsers (ensuring all the HTML5 browsers work as expected) and optionally provides a hash-fallback for HTML4 browsers (including maintained support for data, titles, pushState and replaceState functionality).
You can read more about History.js here:
https://github.com/browserstate/history.js
For an article about Hashbangs VS Hashes VS HTML5 History API, see here:
https://github.com/browserstate/history.js/wiki/Intelligent-State-Handling
HTML5 History API initial load issue
The issue is in this section of code.
$(window).on('popstate', function(e){
var state = e.originalEvent.state;
if(e.originalEvent && state){
loadContent(state);
}
});
If we check the MDN page on Window.onpopstate we find that the state
event property is the state object passed into functions such as pushState
.
the
popstate
event'sstate
property contains a copy of the history entry'sstate
object.
The means that the jQuery event object property e.originalEvent.state
is the object you pass in on pushState
. You could use this object for storing data, but your loadContent
function expects a string for the URL, not an object.
I think you actually want to use document.location
in your popstate
handler.
$(window).on('popstate', function(e){
loadContent(document.location);
});
HTML5 history pushState is not working
Apparently one of the scripts I included had a declaration:
var history = ...;
Unbeknownst to me, all vars on the root actually live in the window scope so the custom history var actually overwrote the original window.history.
Related Topics
How to Change Div Content With JavaScript
How to Autosize a Textarea Using Prototype
How to Get the Pure Text Without HTML Element Using JavaScript
Resize Image With JavaScript Canvas (Smoothly)
How to Validate Inputs Dynamically Created Using Ng-Repeat, Ng-Show (Angular)
Browser/Html Force Download of Image from Src="Data:Image/Jpeg;Base64..."
How to Read Text File in JavaScript
Show Datalist Labels But Submit the Actual Value
Why Does This Simple Jsfiddle Not Work
Export HTML Table Data to Excel Using JavaScript/Jquery Is Not Working Properly in Chrome Browser
How to Send a Json Object Using HTML Form Data
Should Setting an Image Src to Data Url Be Available Immediately
How to Loop Through Selected Elements With Document.Queryselectorall
Passing Variable Through JavaScript from One HTML Page to Another Page