How can I disable HREF if onclick is executed?
Use JavaScript's event.preventDefault()
within the onclick
event handler to disable a link's navigation:
With this code, onclick
will be executed and the href
is practically given a day-off!
Introduce onclick without href
Suppose the JavaScript isn't invited to the party (i.e. it's disabled or even unsupported). We ensure the href
is the go-to guy. Here, the inline return pattern comes to the rescue:
When JavaScript is up and running, onclick
does its thing and return false
shuts the href
down. But if JavaScript isn't around, href
takes the lead.
Embrace addEventListener
Now let's embrace a cleaner method. addEventListener
helps keep HTML and JavaScript separate (because everyone needs their personal space, right?):
This makes your code more flexible, maintainable, and gives you that "coding rockstar" badge!
Dodge the href delay
Delaying the href feels like waiting in a long queue — agonizing. So let's avoid that. Stick to preventDefault()
or return false
. They're immediate, predictable, and won't make your users wait. Can I get a 'hallelujah!'?
Cater to no-JS users
Your users might not know JavaScript exists. In their world, href
should obey. So prepare a plan B: ensure it works without JavaScript. Briefly disable your JavaScript and test this.
Class-based management
For managing multiple elements, use a class as a manager. Let's call it ignore-click
. Now our manager will ensure these links behave as told:
JS on and off: What changes?
Let's cater to both worlds where JavaScript can be on or off. Your onclick
then moulds itself accordingly:
Here, notTodayHref()
is a function deciding if navigation should be controlled.
PHP to the rescue
If server-side logic is a weapon at your disposal, PHP or other server-side languages can be used to decide the href's destiny based on the JavaScript capacity detected either server-side or via cookies.
Simplicity is the ultimate sophistication
You want your solution to be easy to grasp, less of a jigsaw puzzle. Your approach to deactivating href should be simple yet powerful. And while you're at it, take care of accessibility best practices. Every user counts, right?
Was this article helpful?