At first I cannot understand what the first parameter in the pushState function is for? What should I pass on? I just want to change the url while scrolling the page. I am requesting the id of the current item in the viewport, and its id should also be a link in the url. This works well with the code below.
var currentHash, url; if (history && history.pushState) { $(window).scroll(function() { hash = $('.layer:in-viewport').attr('id'); catHash = $("#"+hash).parent('section').attr('id'); var data = "nothing"; if ( catHash != undefined ) url = "/" + catHash + "/" + hash; else url = "/" + hash; if ( currentHash != hash ) { window.history.pushState(data, hash, url); } currentHash = hash; }); }
Now I have two questions:
1.) Right now, the URL in the address bar successfully changes when scrolling the page. How can I request a url / hash in the address bar when I initially loaded the page. So, imagine that I have a link, for example www.url.com/deep . I want to know what / deep? Should I just query the entire top.location and split it into each "/"? I mean, these links don't really exist, so how do I avoid 404 pages when I call the URL that I manipulated with the pushState function?
2.) How do I know the last change in the address bar when I click the "Back" button? So I want to find /deep when I click the browser button so that I can return to that position on the page. I think this probably works with popstate, but I couldn't find out how to do this.
Thank you for your help!
Update:
window.history.pushState("test", hash, url);
...
$(window).bind('popstate', function(event){ console.log(event.data); });
This is always null. Shouldn't this return a "test"?
source share