Anuj Thapa
Anuj Thapa

Reputation: 65

How To Hide Hash Id In The URL Bar Using JavaScript

I want to hide the complete id or hash from the URL for one of mine project but I can't find any solution after searching on internet. actually the problem is related to scroll to div. I have written a JS code which is doing its work in single page application without showing id in URL bar but the problem is that I want to hyperlink a specific div or section of my homepage with another page. It means when a user clicks on that link from another page the user should be redirected or scroll to that particular div after loading the homepage and here JavaScript failed.

WITHOUT JS -

(For example: MY LINK - https://website.com#div-2)

"It's working fine" but the problem is the div id "#div-2" is also visible in the end of the URL and I want to hide it "#div-2". Is there any working solution available for this?

html {
  scroll-behavior: smooth;
}
<a href="#btn-1">BTN 1</a><br>
<a href="#btn-2">BTN 2</a><br>
<a href="#btn-3">BTN 3</a>


<div id="btn-1" style="background-color: red; width:100%; height:600px;"></div>
<div id="btn-2" style="background-color: green; width:100%; height:600px;"></div>
<div id="btn-3" style="background-color: blue; width:100%; height:600px;"></div>

Upvotes: 1

Views: 691

Answers (2)

ddd
ddd

Reputation: 11

@stckvrw

How about listening for the hashchange event? This works for me:

window.addEventListener('load', () => {
    window.history.replaceState('','','/',('#')[0]);
});

window.addEventListener('hashchange', () => {
    window.history.replaceState('','','/',('#')[0]);
});

Used a combination of stckvrw's code, Manjeet Numar Kai's code, and the hashchange event.

Using pushState instead of replaceState is supposed effect browser history entries and back button functionality. I'm getting separate browser entries with both though.

Upvotes: 1

stckvrw
stckvrw

Reputation: 1791

I don't think it's possible WITHOUT JS. So in JS you can use window.history.pushState():

let links = document.querySelectorAll('a[href*="#btn-"]');
links.forEach(link => {
    link.addEventListener('click', () => {
        setTimeout(function() {
            window.history.pushState(document.html, document.title, document.URL.split('#')[0]);
        }, 1);
    });
});

To do the same when page loading:

window.addEventListener('load', () => {
    window.history.pushState(document.html, document.title, document.URL.split('#')[0]);
});

Upvotes: 2

Related Questions