I know there is many questions about this topic on Stackoveflow but i don't understand them.
So my question is how do i remove the #hash in the url (without refresh) after i pressed a link.
Here is one solution but i don't understand where i should put everything
My code is:
<a class="nav-link" href="#home">Home</a>
And #home is the id of the div i want to scroll to.
I know there is many questions about this topic on Stackoveflow but i don't understand them.
So my question is how do i remove the #hash in the url (without refresh) after i pressed a link.
Here is one solution but i don't understand where i should put everything
My code is:
<a class="nav-link" href="#home">Home</a>
And #home is the id of the div i want to scroll to.
Share Improve this question asked Jan 7, 2019 at 19:11 GnussonGnusson 11 silver badge3 bronze badges 6- 2 Hi Gnusson and wele to SO, can you post your code that you have tried so far? I'd be happy to help you work through the solution. – Josh Adams Commented Jan 7, 2019 at 19:13
- Hi josh, i haven't tried any code ): I don't understand where i should put all the code from the example above.. Thanks for your help :D – Gnusson Commented Jan 7, 2019 at 19:14
- If you're navigating to a section in that document you'll need to keep it in. Why do you want to remove it? – Andy Commented Jan 7, 2019 at 19:16
- I think it looks ugly and i know it's possible to delete so thats why. – Gnusson Commented Jan 7, 2019 at 19:18
- That's not a great reason to delete it. – Andy Commented Jan 7, 2019 at 19:19
3 Answers
Reset to default 4If you want the hash link to function normally but just want the hash cosmetically erased, this code might be fine for you:
<!DOCTYPE html>
<html>
<a class="nav-link" href="#home" onClick="removehash()">Home</a>
<div style="height:3000px"></div>
<h1 id="home">HOME</h1>
<script>
function removehash(){
setTimeout(function(){
history.replaceState("", document.title, window.location.pathname);
}, 1);
}
</script>
But the more correct way would probably be to attach a new event that controls the y-offset of the page. That's a bit trickier. Let me know if you're looking for that answer instead.
The easiest way would be replacing the hash with nothing.
location.hash = "";
But if done like this "example.#asdf" bees "example.#"
The less readable way, which also removes the '#' would be pushing a new state to the history.
history.pushState("", document.title, window.location.pathname);
This adds a new entry to the history, without the hash.
if you are using jquery so you can write this in your script file
$(document).ready(function(){
$('.nav-link').click(function(e){ e.preventDefault(); })
})