Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

location.hash and back history

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?

like image 611
George Filippakos Avatar asked Jul 13 '12 12:07

George Filippakos


People also ask

What is the location hash?

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.

What does Window location hash return?

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.

What is a hash in a URL?

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.

What is a browser hash?

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.


2 Answers

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

like image 144
jalbee Avatar answered Oct 04 '22 05:10

jalbee


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.

like image 35
Charles Avatar answered Oct 04 '22 04:10

Charles