Home >Web Front-end >JS Tutorial >Why URL hashes are my favorite way to fire events

Why URL hashes are my favorite way to fire events

WBOY
WBOYOriginal
2024-08-16 18:37:25386browse

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?

The above is the detailed content of Why URL hashes are my favorite way to fire events. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn