DEV Community

Cover image for Why URL hashes are my favorite way to fire events
breakfast
breakfast

Posted on

Why URL hashes are my favorite way to fire events

As a young web developer, I often wondered what the best way to fire events was (for example, to make a link display new content on the page, without reloading). I considered using HTML elements as event handlers, by changing a property when firing an event—but this just seemed too in the way. I needed something out of the way of my HTML.

I then looked at my URL bar, sitting there lonely and unused, and an idea came to me. I would simply add two URL parameters, one named event and one named data! It was perfect!

Or so I thought. Adding URL parameters reloads the page, so this wouldn't work either. But I still thought the URL was the best way to go, and reminded myself of hashes.

For those who don't know, adding hashes to a URL does not reload the page.

I have used this technique ever since then, and it is undoubtedly my favorite. I don't believe this is a usual technique. All I know is that it suits my needs.

window.addEventListener("hashchange", function(hash) {
  if (hash === "#profile-19289948") {
    ...
  }
});
Enter fullscreen mode Exit fullscreen mode

Now I'm curious—do other people do something similar? Do other people even know what I'm talking about?

Top comments (1)

Collapse
 
greenersoft profile image
GreenerSoft

Old technique, but search engines don't crawl any part of the URL past the hash.