skip to Main Content

When you click a link in a navigation bar, it scrolls to a section of the page that it’s linked to. However, it leaves #section_name in the URL.

I was wondering if there was a way to remove this or even just git rid of the #. It makes the URL look a little ugly (IMO).

2

Answers


  1. try this

    document.getElementById('thing1').addEventListener('click', function(e) {
      e.preventDefault();
      const thing2 = document.getElementById('thing2');
      const thing2position = thing2.getBoundingClientRect();
      window.scrollTo({
        top: thing2position.top + window.scrollY,
        left: thing2position.left + window.scrollX,
        behavior: 'smooth'
      });
    });
    document.getElementById('thing2').addEventListener('click', function(e) {
      e.preventDefault();
      const thing1 = document.getElementById('thing1');
      const thing1position = thing1.getBoundingClientRect();
      window.scrollTo({
        top: thing1position.top + window.scrollY,
        left: thing1position.left + window.scrollX,
        behavior: 'smooth'
      });
    });
    #thing2{
      position: absolute;
      top: 1000px;
    }
    <body>
        <a href="#" id="thing1">first thing</a>
        <a href="#" id="thing2">second thing</a>
    </body>
    Login or Signup to reply.
  2. Yes, this should work without changing the URL, but it uses JavaScript:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Example</title>
    </head>
    <body>
    
        <a href="#content1" class="scroll-link">Go to Content 1</a>
        <a href="#content2" class="scroll-link">Go to Content 2</a>
    
        <div id="content1">      
            <h2>This is the content 1</h2>
            <p>Here is some example content.</p>
        </div>
        
        <div id="content2">      
            <h2>This is the content 2</h2>
            <p>Here is some example content.</p>
        </div>
    
        <script>
            const scrollLinks = document.querySelectorAll('.scroll-link');
    
            scrollLinks.forEach(function(link) {
                link.addEventListener('click', function(event) {
                    event.preventDefault();
                    const targetId = this.getAttribute('href');
                    document.querySelector(targetId).scrollIntoView();
                });
            });
        </script>
    
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search