-1

I have a one page website which has the following link to a section

<a href="#section1">Section 1</a>

<div id="#section1>
TEXT
</div>

When I click on the link in the URL it has the #section1 at the end - is it possible to remove this?

The site is hosted on a ngix server

DBS
  • 9,110
  • 4
  • 35
  • 53
Jay
  • 25
  • 6
  • 1
    That URL hash is how the page jumps to a section, you could use JS to remove it after navigating, but I don't believe you can avoid it being added in the first place. (And if you're using JS, you could just use that to do the scrolling without the hash) – DBS May 18 '23 at 12:22
  • Why do you want to avoid showing the URL you are visiting in the address bar? – Quentin May 18 '23 at 12:22
  • also: 1) https://stackoverflow.com/questions/15223006/scroll-with-anchor-without-in-url; 2) https://stackoverflow.com/questions/39596532/html-link-to-anchor-without-changing-url and other numerous duplicate posts !! – OMi Shah May 18 '23 at 12:26

1 Answers1

0

You can do it using JavaScript but it's not necessary.

<a class="navigate" href="#section-1">Scroll</a>

<script>
document.querySelector('.navigate').forEach(( a ) => {
  a.addEventListener('click', (ev) => {
    ev.preventDefault();
    const id = ev.target.id;
    document.getElementById(id).scrollIntoView();
  })
})

Here we prevent the default action when clicking the link by using preventDefault. Then using JavaScript we get the ID of the element and scroll to the view using JavaScript.

Note that to make that function reusable, we add the class navigate to all the anchors that have the same behavior

Ahmad Alfy
  • 13,107
  • 6
  • 65
  • 99