The hash key(#) in the URL

1. The meaning of #

The hash key(#) also known as anchor in a web page, represents a position on the web page, and the character on the right is the identifier of that position.

http://www.example.com/index.html#section

It represents the “section” position in index.html. The browser will automatically scroll the “section” position to the visible area of the page.

Here is an example of how to use # to locate the position you want.

  1. Set an anchor point <a href=’#section’>locate at the ‘section’ position</a>;
  2. Add id=”section” to the tag that needs to be located on the page. Like: <div id=”section”></div>

Click the anchor point set in step 1, and the page will automatically scroll to the div whose id attribute is “section”. At the same time, the hash value of #section will appear at the end of the URL.

2. In a HTTP request, the content after the hash key will not be sent to the server

The hash key(#) is used to guide the browser’s actions and is completely useless to the server side. Therefore, # is not included in the HTTP request.

You can visit the following website:

https://stackoverflow.com/?key=#abc

As the request head shows:

As you can see, only https://stackoverflow.com is requested, and there is no request for “#abc”.

3. The characters after the hash key

Any character that appears after the first # will be interpreted as a location identifier by the browser. This means that none of these characters will be sent to the server. But what if we really need to send a # to the server. It’s very simple, you just replace # with %23. Like this:

https://stackoverflow.com/?key=%23abc

Now the #abc can be sent to the server:

4. Content changes after the # will not trigger web page reload

Just change the content after hash key(#), the browser will only scroll to the target location, and will not reload the web page. The browser will not request the page from the server again.

5. Changing the content after the # will change the browser’s historical access page

Every time you change the part after #, a log will be added to the browser’s visit history. We can use the “back” button to return to the previous page.

This is particularly useful for SPA(single-page application). You can use different # values to indicate different access states, and then give users a link to access a certain state.

But this point are not valid for IE 6 and IE 7. They will not increase the history record due to the change of #.

6. onhashchange event

This is a new event in HTML 5, which will be triggered when the # value changes. Most common browsers support this event. We can use it in the following ways:

  1. window.onhashchange = func
  2. <body onhashchange=”func();”>
  3. window.addEventListener(“hashchange”, func, false);

RSS