Explain Codes LogoExplain Codes Logo

How do I disable a href link in JavaScript?

javascript
javascript-features
link-management
event-listeners
Alex KataevbyAlex Kataev·Sep 27, 2024
TLDR

Nullify the click event of a link using preventDefault():

document.getElementById('linkId').onclick = function(e) { e.preventDefault(); };

Or drop the href to disarm it:

document.getElementById('linkId').removeAttribute('href');

Visually gray out and deactivate links with some handy CSS:

.disable-link { pointer-events: none; /* ✋ Stop! You shall not pass! */ color: grey; /* Visually disable the link */ }

Apply this class dynamically with JavaScript:

document.getElementById('linkId').classList.add('disable-link');

Caution! Check for pointer-events: none; support across target browsers as older browsers may not be friendly with it.

Function to turn link activity on and off based on conditions:

function toggleLinkActivity(linkId, isActive) { const link = document.getElementById(linkId); if (isActive) { link.classList.remove('disable-link'); link.href = 'http://example.com'; // Welcome back to the party! } else { link.classList.add('disable-link'); link.removeAttribute('href'); // Party's over, guys. } }

B: Guarding against inadvertent navigation

Prevent surprise scares from unexpected navigation. Don't let your users astray:

window.addEventListener('load', () => { const links = document.querySelectorAll('a[href]'); links.forEach(link => { if (/* some scary condition */) { link.onclick = e => e.preventDefault(); // 👻 Not today, ghosts! } }); });

C: jQuery to the rescue!

For jQuery fans, link disabling is as short and sweet as a tweet:

$('a').on('click', function(e) { if (/* some condition */) { e.preventDefault(); // jQuery says, "Stay put!" } });

Method 3: Sharp shooting your target elements

Be sure you're hitting the right target to avoid friendly fire with other clickable elements:

document.querySelectorAll('.specific-class a').forEach((link) => { link.onclick = (e) => e.preventDefault(); });

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.

To deactivate a specific link without an id, set its href attribute to the current page's URL:

const currentUrl = window.location.href; document.querySelector('a#troublemakerLink').href = currentUrl; // You're grounded!

Stripping off href using removeAttribute

The removeAttribute method completely disables the link, more robust than setting href to null or "":

document.getElementById('linkId').removeAttribute('href'); // Link, you're fired!

Consult MDN documentation in the references for a deep dive into this method.