Friday, March 7, 2014

Javascript & Hash-Less Page Navigation

When adding a new row to a form I was dealing with the "Add" button being at the top of the form and the new row being added to the bottom. After the user has added a lot of new rows I wanted to user location.hash in the javascript adding the new row html to make sure the new row is in view.

However, I didn't want the hash #newrow to be left in the URL bar.

If you try to use location.hash = "newrow"; followed by location.hash = ""; you still have the "#" sign in there AND it scrolls the page position back to the top. Not good.

I found some javascript which resets the url history state without the hash:

history.pushState("", document.title, window.location.pathname +;

Using this immediately after setting the hash works perfectly for Hash-Less page navigation:

location.hash = "newrow";
history.pushState("", document.title, window.location.pathname +;

This works in both FF and Chrome.

No comments: