How do I disable a href
link in JavaScript?
Nullify the click event of a link using preventDefault()
:
Or drop the href
to disarm it:
Method 1: Using CSS to deactivate links
Visually gray out and deactivate links with some handy CSS:
Apply this class dynamically with JavaScript:
Caution! Check for pointer-events: none;
support across target browsers as older browsers may not be friendly with it.
Method 2: Dynamic link management with JavaScript
A: Crafting a switch to handle link activity
Function to turn link activity on and off based on conditions:
B: Guarding against inadvertent navigation
Prevent surprise scares from unexpected navigation. Don't let your users astray:
C: jQuery to the rescue!
For jQuery fans, link disabling is as short and sweet as a tweet:
Method 3: Sharp shooting your target elements
Be sure you're hitting the right target to avoid friendly fire with other clickable elements:
Going beyond - advanced navigation
Handling mobile swipes and taps
On mobile web interactions, link disabling might play differently. Always ensure to test on multiple devices for a consistent experience.
Disabling that one troublesome link
To deactivate a specific link without an id
, set its href
attribute to the current page's URL:
Stripping off href
using removeAttribute
The removeAttribute
method completely disables the link, more robust than setting href
to null
or ""
:
Consult MDN documentation in the references for a deep dive into this method.
Was this article helpful?