"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why URL hashes are my favorite way to fire events

Why URL hashes are my favorite way to fire events

Published on 2024-08-18
Browse:525

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") {
    ...
  }
});

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

Release Statement This article is reproduced at: https://dev.to/sillybreakfast/why-url-hashes-are-my-favorite-way-to-fire-events-1415?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3