I am ajax-ifying the pagination in one of me projects and since I want the users to be able to bookmarks the current page, I am appending the page number via hash, say:
onclick="callPage(2); window.location.hash='p=2'; return false;"
and thats on the hyperlink
it works fine and everything, except, when the page number is 1, i dont want to URL
to be /products#p=1
, I just want it to be /products
I tried these variations:
window.location.hash=''
works but the url is now like /products#
and I dont quite the hash there./products#p=3
since I am not messing with the hash.<a href="#">
and he should use javascript:void(0)
instead. (had they never heard of Ajax?)So finally, I decided to make this thread, I found several similar threads here, but all the answers ls very similar to my second point.
so my big question still remains a question: How to kick the hash out of the URL and possibly out of the universe? (only for the first page!)
To remove the hash URL, you can use the replaceState method on the history API to remove the hash location. Example: HTML.
A hash sign (#) in a URL is referred to as a fragment. Historically, URL fragments have been used to automatically set the browser's scroll position to a predefined location in the web page. In that sense, if a URL refers to a document, then the fragment refers to a specific subsection of that 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.
history.pushState("", document.title, window.location.pathname);
Updated Answer:
Best way to achieve this is to follow Homero Barbosa's answer below:
history.pushState("", document.title, window.location.pathname);
... or, if you want to maintain the search parameters:
history.pushState("", document.title, window.location.pathname + window.location.search);
Original Answer, do not use this, badwrongfun:
var loc = window.location.href, index = loc.indexOf('#'); if (index > 0) { window.location = loc.substring(0, index); }
... but that refreshes the page for you which seems a trifle rude after just arriving there. Grin and bear it seems to be the best option.
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