How7o
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Run Code on URL Hash Change in JavaScript
Share
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > How to Run Code on URL Hash Change in JavaScript
Web Development

How to Run Code on URL Hash Change in JavaScript

how7o
By how7o
Last updated: May 22, 2026
4 Min Read
Run JS code on URL hash change with the hashchange event
SHARE

To run code when the URL hash changes in JavaScript, listen for the hashchange event on window. The browser doesn’t reload when only the hash changes — your handler runs each time it does, so you can branch on location.hash without forcing a page refresh.

Contents
  • The hashchange event
  • Force a reload on hash change (if you really need it)
  • React to the initial hash on page load too
  • Read old and new hash from the event
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-05-17 in Chrome 124, Firefox 125, Safari 17. Originally published 2022-08-28, rewritten and updated 2026-05-17.

The hashchange event

window.addEventListener('hashchange', () => {
    if (location.hash === '#step2') {
        // show tutorial step 2
    }
});

Every time the hash part of the URL changes — programmatically or via a click on a same-page anchor — the listener fires. No reload, no loss of in-memory state.

URL hash change in JS — hashchange event, addEventListener, location.reload fallback

Force a reload on hash change (if you really need it)

window.addEventListener('hashchange', () => {
    location.reload();
});

Almost never the right call — the whole point of a hash change is that it’s cheap and in-memory. But if your initial render only handles the hash at page load, a reload is the quickest fix.

React to the initial hash on page load too

function handleHash() {
    const step = location.hash.slice(1);   // 'step2' without the #
    if (step === 'step2') {
        // ...
    }
}

window.addEventListener('hashchange', handleHash);
window.addEventListener('DOMContentLoaded', handleHash);

hashchange doesn’t fire on the very first page load — only on subsequent changes. Run the same handler on DOMContentLoaded (or just inline at the bottom of the script) so the initial hash is also handled.

Read old and new hash from the event

window.addEventListener('hashchange', (event) => {
    console.log('Old:', event.oldURL);
    console.log('New:', event.newURL);
});

The event object exposes oldURL and newURL — full URLs, not just the hash. Useful for tracking transitions like “user went from #step1 to #step3” for analytics or transition animations.

Frequently asked questions

Why doesn’t the page reload when only the hash changes?

Hash-only navigations are explicitly designed to not reload — they’re meant for in-page jumps (anchor links) and SPA routing. The browser treats example.com/page#step1 and example.com/page#step2 as the same document, just with a different fragment. The hashchange event exists precisely so you can react to that change without a reload.

Should I prefer window.onhashchange = ... or addEventListener?

addEventListener('hashchange', ...) is the modern recommendation. Multiple listeners can coexist on the same event, and there’s no risk of accidentally overwriting another script’s handler — which can happen with window.onhashchange = .... Same browser support.

How do I read the hash without the leading #?

location.hash includes the # (e.g. '#step2'). Strip it with .slice(1) or use the URL constructor: new URL(location.href).hash.slice(1). The History API’s pushState equivalent (history.state) doesn’t include hash semantics.

Do I need hashchange if I’m using the History API?

If you push real URLs (history.pushState({}, '', '/step2')), use popstate instead. hashchange only fires for the #fragment part. Most SPA routers use pushState/popstate now; hashchange is best for lightweight in-page state without true route changes.

Related guides

  • How to Check if a JavaScript String Is a Valid URL
  • How to Check the HTTP Referrer with JavaScript
  • How to Disable or Enable an Input with JavaScript or jQuery

References

MDN hashchange event: developer.mozilla.org/en-US/docs/Web/API/Window/hashchange_event. MDN Location.hash: developer.mozilla.org/en-US/docs/Web/API/Location/hash.

TAGGED:browserdomJavaScript

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Nginx redirect www to non-www or vice versa How to Redirect www to non-www (or vice versa) in Nginx
Next Article Reload DataTables with a new Ajax URL How to Reload DataTables with a New Ajax URL
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

FacebookLike
XFollow
PinterestPin
InstagramFollow
Most Popular
Set vi as the default editor in Ubuntu — a terminal opening the vim editor
How to Set vi (Vim) as the Default Editor in Ubuntu
June 8, 2026
rsync says ALL DONE but files are missing — a terminal showing ALL DONE next to an empty folder
rsync Says “ALL DONE” but Files Are Missing: How to Verify
June 8, 2026
Migrate a website to a new server with rsync — files copying from an old server to a new one over SSH
How to Migrate a Website to a New Server With rsync
June 8, 2026
Bun runtime — faster JS toolkit replacing npm in Laravel projects
How to Install Bun Runtime on Ubuntu (And Use It in a Laravel Project)
May 24, 2026
Tailscale mesh — peer-to-peer connections between devices, coordination server
How to Install Tailscale on Ubuntu (Zero-Config Mesh VPN for Self-Hosters)
May 24, 2026

You Might Also Like

Laravel MySQL variable in select — @name := assignment chains values across select items
Web Development

How to Set a MySQL Variable in Laravel Query Builder Select

8 Min Read
CSS checkbox background color — accent-color one-liner and hide-and-replace fallback
Web Development

How to Change a Checkbox Background Color with CSS

5 Min Read
Store a PHP array in a MySQL database with JSON
Web Development

How to Store a PHP Array in a MySQL Database

5 Min Read
Get the selected radio button value with jQuery
Web Development

How to Get the Selected Radio Button Value in jQuery

3 Min Read
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Tools

  • Age Calculator
  • Word Counter
  • Image Upscaler
  • Password Generator
  • QR Code Generator
  • See all tools→

Pranks

  • Fake Blue Screen Prank
  • Hacker Typer
  • Fake iMessage Generator
  • Windows XP Crash Prank
  • Windows 11 Update Prank
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?