Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I change sections in HTML without getting '#' in the Link?

Hi

So, while making a website I noticed that when I am redirecting between sections in HTML using ‘a’ tag I am getting the link as ‘www.example.com#section’.’

This is the code:

<a href="#section">Change Section</a>
<section class="section">
 <p> Hi </p>
</section>

I want the link as ‘www.example.com/section’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I wanna know how to do this change.

>Solution :

This is just how URLs work.

  • https:// determines how to ask for the resource
  • www.example.com determines what server to ask for it from
  • /some/path/?query=optional determines what to ask the server for
  • #fragment is handled client-side and determines where the browser scrolls to on the page

There isn’t a sensible way to make the part of the URL that is sent to the server be treated as the part the browser uses to determine where to scroll to.


If you want to head down routes that are not sensible…

  1. Make the server-side code deliver the same HTML document for every /path you want to represent a part of the same page
  2. Mark the primary URL as canonical
  3. Add some client-side JS that:
    1. waits for the DOMContentLoaded event
    2. Reads the location to get the path
    3. Uses some internal logic to determine what element to scroll to
    4. Uses scrollTo to scroll to it/Element/scrollTo
  4. Add some more client-side JS that:
    1. Listens for click events on your internal links
    2. uses pushState and preventDefault to change the URL without leaving the current (identical) page
    3. Reads the URL from the href of the clicked link
    4. Does the same as steps 3.3 and 3.4
  5. Add some more client-side JS that
    1. listens for popstate events
    2. gets the URL the user is going back to
    3. Does the same as steps 3.3 and 3.4

… now that’s a lot of work to make URLs act in a non-standard way.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading