Change URL hash without page jump

In modern complex layouts, sometimes the point where a hash will transport you to will be entirely different than the one you actually wanted. If you prevent the default event, you will save yourself from the page jump, but the hash won’t change either…


This content originally appeared on Lea Verou’s blog and was authored by Lea Verou

In modern complex layouts, sometimes the point where a hash will transport you to will be entirely different than the one you actually wanted. If you prevent the default event, you will save yourself from the page jump, but the hash won’t change either. You can accept the regular behavior and change scrollTop after the jump, but the user will still see a distracting flicker. Chris Coyier found a great workaround last year but it’s not meant for every case.

A different solution

Turns out we can take advantage of the History API to do that quite easily. It’s just one line of code:

history.pushState(null, null, ‘#myhash’);

and we can combine it with the old method of setting location.hash to cater for older browsers as well:

if(history.pushState) { history.pushState(null, null, ‘#myhash’); } else { location.hash = ‘#myhash’; }

Browser support?

The History API is supported by:

  • Firefox 4+
  • Safari 5+
  • Chrome 8+
  • Coming soon in Opera

Enjoy :)


This content originally appeared on Lea Verou’s blog and was authored by Lea Verou


Print Share Comment Cite Upload Translate Updates
APA

Lea Verou | Sciencx (2011-05-13T00:00:00+00:00) Change URL hash without page jump. Retrieved from https://www.scien.cx/2011/05/13/change-url-hash-without-page-jump/

MLA
" » Change URL hash without page jump." Lea Verou | Sciencx - Friday May 13, 2011, https://www.scien.cx/2011/05/13/change-url-hash-without-page-jump/
HARVARD
Lea Verou | Sciencx Friday May 13, 2011 » Change URL hash without page jump., viewed ,<https://www.scien.cx/2011/05/13/change-url-hash-without-page-jump/>
VANCOUVER
Lea Verou | Sciencx - » Change URL hash without page jump. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2011/05/13/change-url-hash-without-page-jump/
CHICAGO
" » Change URL hash without page jump." Lea Verou | Sciencx - Accessed . https://www.scien.cx/2011/05/13/change-url-hash-without-page-jump/
IEEE
" » Change URL hash without page jump." Lea Verou | Sciencx [Online]. Available: https://www.scien.cx/2011/05/13/change-url-hash-without-page-jump/. [Accessed: ]
rf:citation
» Change URL hash without page jump | Lea Verou | Sciencx | https://www.scien.cx/2011/05/13/change-url-hash-without-page-jump/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.