Why URL hashes are my favorite way to fire events
breakfast
Posted on August 16, 2024
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") {
...
}
});
Now I'm curious—do other people do something similar? Do other people even know what I'm talking about?
Posted on August 16, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.