DEV Community

Emrah G.
Emrah G.

Posted on

Opening Modals with Hash Listeners: A Simple JavaScript Pattern

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

  1. Listen for the hashchange event on window.
  2. When the URL hash matches your trigger (#upgrade, for example), open the modal.
  3. 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);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

You would also need to attach this function:

window.addEventListener("hashchange", handleOpenModal, { passive: true });
Enter fullscreen mode Exit fullscreen mode

🔑 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. 🚀

Top comments (0)