Is there a function that can be called to prevent the browser from recording a back history entry when changing the hash value?
I am writing a simple javascript gallery that changes the browser url without reloading the page as the user moves through each image.
This is done by setting the location.hash to the unique ID of the image.
window.location.hash = imageID;
The problem is when the user hits the browser back button, they must move backwards through every image like it was a page load.
If they rotated through 20 images using the gallery, they must click back 21 times to get back to the previous page.
How can I prevent a back history from being recorded with javascript?
hash. The hash property of the Location interface returns a string containing a '#' followed by the fragment identifier of the URL — the ID on the page that the URL is trying to target. The fragment is not percent-decoded.
The window. location. hash returns a string that contains a # along with the fragment identifier of the URL. The fragment identifier of the URL starts with a # followed by an identifier that uniquely identifies a section in an HTML document.
In a URL, a hash mark, number sign, or pound sign ( # ) points a browser to a specific spot in a page or website. It is used to separate the URI of an object from a fragment identifier. When you use a URL with a # , it doesn't always go to the correct part of the page or website.
A browser hash is a string of numbers and letters created to map data related to a user's browser. In a way, it serves as the browser's ID, used to identify the browser and user by the party who created the hash to begin with.
window.location.replace
will let you set the url without adding it to the browser history.
var baseUrl = window.location.href.split('#')[0];
window.location.replace( baseUrl + '#' + imageID );
documentation
You can use replaceState().
Before you change the hash you save the history, then you change your hash, finally you replace the history with the one you saved.
Alternatively you can use popState Event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With