This content originally appeared on DEV Community and was authored by Emrah G.
Sometimes you want to share a URL that opens a modal dialog immediately.
Instead of forcing users to click buttons, you can leverage hash fragments (#something
) and the native hashchange
event to trigger the modal.
This approach works with plain JavaScript (or any framework like React, Vue, or Svelte) and keeps your app deep-linkable.
🚀 The Core Idea
- Listen for the
hashchange
event onwindow
. - When the URL hash matches your trigger (
#upgrade
, for example), open the modal. - Clean up the hash so it can be triggered again later.
🛠️ The handleOpenModal
Function
Here’s a simplified version of the logic:
function handleOpenModal() {
// Only trigger if the hash includes our keyword
if (window.location.hash.toLowerCase().includes("#upgrade")) {
// Open the modal (pseudo-code)
openModal();
// Clean the hash so the same link can be used again
const { pathname, search, hash } = window.location;
let cleanedHash = hash.replace("#upgrade", "").trim();
const newUrl = pathname + search + (cleanedHash ? `#${cleanedHash}` : "");
try {
// Replace the current history entry so the back button isn’t broken
window.history.replaceState(window.history.state, "", newUrl);
} catch {
// Fallback in stricter environments
window.location.replace(newUrl);
}
}
}
You would also need to attach this function:
window.addEventListener("hashchange", handleOpenModal, { passive: true });
🔑 Why This Works
Shareable deep links → In my case I send https://routebot.com + #upgrade (like mysite.com#upgrade) and the modal opens right away.
Back button safety → Cleaning the hash prevents broken navigation.
Reusable → Same link can open the modal multiple times.
🌍 Real-World Use Case
I use this exact technique in RouteBot 🚍, where admins can send deep links that trigger upgrade flows or onboarding modals instantly.
Instead of saying “click here, then press upgrade”, one URL just opens the right dialog.
âś… Wrap-Up
Hash listeners are a lightweight, framework-agnostic solution for modals triggered by links.
No extra query params
No heavy router logic
Just plain JavaScript
If you’re building SaaS, consider this pattern to simplify onboarding or upgrades.
And if you’re into transport SaaS and optimization, check out RouteBot
— we use patterns like this every day. 🚀
This content originally appeared on DEV Community and was authored by Emrah G.

Emrah G. | Sciencx (2025-09-10T04:58:49+00:00) Opening Modals with Hash Listeners: A Simple JavaScript Pattern. Retrieved from https://www.scien.cx/2025/09/10/opening-modals-with-hash-listeners-a-simple-javascript-pattern-3/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.