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
Run Laravel queue workers with Supervisor
How to Run Laravel Queue Workers in Production with Supervisor
May 23, 2026
Nginx as a reverse proxy for a Node.js app on Ubuntu
How to Set Up Nginx as a Reverse Proxy for Node.js on Ubuntu
May 23, 2026
Install and configure Redis on Ubuntu for Laravel and WordPress
How to Install and Configure Redis on Ubuntu (for Laravel & WordPress)
May 23, 2026
Harden a fresh Ubuntu VPS with UFW, Fail2Ban, and SSH key auth
How to Harden a Fresh Ubuntu VPS: UFW + Fail2Ban + SSH Key Auth
May 23, 2026
Set up Let's Encrypt SSL with Certbot on Ubuntu
How to Set Up Let’s Encrypt SSL with Certbot on Ubuntu (Apache & Nginx)
May 23, 2026

You Might Also Like

Rename menu items on the WooCommerce My Account page
Web Development

How to Rename Menu Items on the WooCommerce My Account Page

4 Min Read
jQuery check if a checkbox is checked
Web Development

How to Check if a Checkbox Is Checked with jQuery

4 Min Read
DataTables default sort order — order: [[1, 'desc']] config
Web Development

How to Change the Default Sort Order in DataTables

4 Min Read
PHP delete array element — unset, array_splice, array_filter, array_search
Web Development

How to Delete an Element from a PHP Array

7 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?