I’ve come across the following href
expression in various webpages:
<a href="javascript:;"></a>
I’m curious about what this does and the reasoning behind using it. Is it related to JavaScript on page load, or does it serve some other purpose in the page’s behavior? Can someone explain this technique?
So, this href="javascript:;"
expression? It’s pretty classic in web development. It creates a clickable link without navigating anywhere. Here’s what’s going on:
<a href="javascript:;"></a>
The href="javascript:;"
is essentially telling the browser to ‘run JavaScript, but don’t actually do anything.’ The semicolon (;
) is a placeholder that does nothing, basically a no-op.
Why it’s used:
It’s used when you want something to act like a link (clickable) but not redirect to a different page or location. It’s an old-school hack in the world of href javascript
. A lot of early developers used this to simulate buttons without the risk of causing any page navigation.
Exactly, Jacqueline! You often see href="javascript:;"
in web pages tied to JavaScript event handlers. For example:
<a href="javascript:;" onclick="openModal()">Click me</a>
What’s happening here:
In this case, the logic (like opening a modal or triggering a dropdown) is inside the onclick
event handler. The href="javascript:;"
ensures that the link looks and feels like a clickable element, but it doesn’t actually navigate the page. It’s all about running the JS without side effects.
Why not just use #
?
Good question! People often avoid using href="#"
because clicking it might unexpectedly scroll the page to the top, which can be annoying. On the other hand, href="javascript:;"
has no side effects and doesn’t interfere with the page’s scroll position, which is why it’s preferred in this case.
It’s outdated and there are better modern options
While href javascript is still functional, today developers prefer:
<a href="#" onclick="..."> <!-- (scrolls page) -->
<!-- OR -->
<button onclick="..."> <!-- (semantic and accessible) -->
Why switch?
Using a <button>
for actions is semantically correct and better for accessibility. So if you’re writing new code, try to avoid the href javascript approach—it’s more of a legacy pattern.