CodersTechZone
  • .NET
    • C#
    • ASP.Net
  • HTML
  • Javascript
  • CSS
  • Database
    • SQL Server
    • MYSql
    • Oracle
  • AI
  • TechNews
  • Web-Stories

JavaScript Disable Anchor: A Comprehensive Guide

Shawpnendu Bikash Maloroy

July 11, 2024
JavaScript Disable Anchor - A Comprehensive Guide
Spread the love

JavaScript disable anchor tags means you need to disable anchor tags to prevent users from clicking on them. If you want to remove a link behavior completely, you can remove the href attribute easily. If not possible, then there are many ways to disable anchors, like using the preventDefault() method, using CSS, or using return false in response to an onclick event.

In this article, we will explore all popular methods to disable anchor tags, using very simple and practical examples. This will help you a lot to control user navigation and improve the user experience on your website.

Table of Contents

  • Why Disable Anchor Tags?
  • JS Methods to Disable Anchor Tags
    • 1. Using JS preventDefault() Method
      • Output
    • 2. Using a Disabled Class
      • output
      • code explanation
    • 3. Disable Using a Wrapper Function
  • JavaScript Disable Anchor Tag: Additional Techniques
    • Disable Using tabindex and aria-disabled
      • Code explanation
    • Disable All Links on DOMContentLoaded
      • output
    • Removing the href Attribute
      • output
    • Form Validation
      • output
  • Table of Methods and Use Cases
  • Best Practices for Disabling Anchors
  • Conclusion

Why Disable Anchor Tags?

Disabling anchor tags can be useful for several reasons:

  • Prevent Navigation: Stop users from navigating links.
  • Conditional Access: Enable or disable links based on user permissions or other conditions.
  • Improving User Experience: Avoid navigation errors or redundant clicks by disabling irrelevant links.

JS Methods to Disable Anchor Tags

1. Using JS preventDefault() Method

The preventDefault() method can stop any default action of an event, such as navigating to a link.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Disable Anchor Example</title>
</head>
<body>
    <a href="https://coderstechzone.com" id="myLink">Visit our JS Blog Now ....</a>

    <script>
        document.getElementById('myLink').addEventListener('click', function(event) {
            event.preventDefault();
            console.log('This link is disabled. And the click event won\'t redirect ..');
        });
    </script>
</body>
</html>
Output
JavaScript disable anchor – using preventDefault() method

2. Using a Disabled Class

You can use a CSS class to visually style a disabled link. Combine your CSS styles with the JavaScript preventDefault() method to prevent navigation, like below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Disable Anchor Example</title>

    <style>
      .disabled {
          pointer-events: none;
          color: gray;
          text-decoration: none;
      }
  </style>

</head>

<body>
    <a href="https://coderstechzone.com" id="myLink" class="disabled">Visit coderstechzone.com</a>

    <script>
        document.getElementById('myLink').addEventListener('click', function(event) {
            event.preventDefault();
        });
    </script>
</body>
</html>
output
JavaScript disable anchor - using preventDefault() method with css class
Link disabled..
code explanation

Here, we update the HTML markup of our anchor tag with the CSS class “disabled”. In order to give the user a visual vibe that the link is not clickable, the pointer style should not change when they mouse over it. Afterwards, we programmatically disable the anchor tag within the click event callback function using the preventDefault() method.

buymeacoffee

3. Disable Using a Wrapper Function

You can wrap the anchor in a function that checks your conditions first before allowing navigation. Do this like below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Disable Anchor Example</title>
</head>
<body>
    <a href="https://coderstechzone.com" id="myLink">Visit coderstechzone.com</a>

    <script>
        function checkLink(event) {
            const isDisabled = true; // Handle based on your condition
            if (isDisabled) {
                event.preventDefault();
                console.log('This link is disabled.');
            }
        }

        document.getElementById('myLink').addEventListener('click', checkLink);
    </script>
</body>
</html>

JavaScript Disable Anchor Tag: Additional Techniques

Disable Using tabindex and aria-disabled

For better accessibility, use tabindex and aria-disabled attributes like below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Disable Anchor Example</title>
    <style>
        .disabled {
            color: gray;
            pointer-events: none;
        }
    </style>
</head>
<body>
    <a href="https://coderstechzone.com" id="myLink" class="disabled" tabindex="-1" aria-disabled="true">Visit coderstechzone.com</a>

    <script>
        document.getElementById('myLink').addEventListener('click', function(event) {
            event.preventDefault();
            alert('This link is disabled.');
        });
    </script>
</body>
</html>
Code explanation
  • tabindex=”-1″: Removes the link from the tab order.
  • aria-disabled=”true”: Indicates the link is disabled for screen readers.

Disable All Links on DOMContentLoaded

If you want to disable all links of your page upon page load completion then you can follow the below code block:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Disable Anchor Example</title>
</head>
<body>
    <a href="https://coderstechzone.com" id="myLink">Visit coderstechzone.com</a><br><br>
    <a href="https://developer.mozilla.org/" id="myLink2">Visit MDN.com</a>

    <script>
      // You can add other events
      document.addEventListener('DOMContentLoaded', function() {
          const anchorLinks = document.querySelectorAll('a');
          anchorLinks.forEach(link => {
              link.addEventListener('click', function(e) {
                // Prevent the default anchor link behavior  
                e.preventDefault();
                console.log(e.target.id +' is not a clickable link ....');
              });
          });
      });
    </script>
</body>
</html>
output
JavaScript disable anchor – Disable All Links

Removing the href Attribute

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Disable Anchor Example</title>
</head>
<body>
    <a href="https://coderstechzone.com" id="myLink">Visit coderstechzone.com</a><br><br>
    <a href="https://developer.mozilla.org/" id="myLink2">Visit MDN.com</a>
    <br><br><br>
    <button type="button" id="myButton">Remove Href  Now ...</button>

    <script>
      document.getElementById('myButton').addEventListener('click', function(event) {
          document.getElementById("myLink2").removeAttribute("href");
          console.log('Removed successfully !!');

        });
    </script>
</body>
</html>
output
JavaScript disable anchor – Removing the href Attribute
buymeacoffee

Form Validation

In the following form validation example, we are using one input box and one button in our HTML markup. Initially, the submit button is disabled and will be enabled once the user starts to write something in the input box.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Validation Example</title>
    <style>
        .disabled {
            color: gray;
            pointer-events: none;
        }
    </style>
</head>
<body>
    <form id="myForm">
        <input type="text" id="username" placeholder="Enter username">
        <a href="#" id="submitLink" class="disabled">Submit</a>
    </form>

    <script>
        document.getElementById('username').addEventListener('input', function() {
            const submitLink = document.getElementById('submitLink');
            if (this.value.trim() !== '') {
                submitLink.classList.remove('disabled');
                submitLink.removeAttribute('tabindex');
                submitLink.removeAttribute('aria-disabled');
            } else {
                submitLink.classList.add('disabled');
                submitLink.setAttribute('tabindex', '-1');
                submitLink.setAttribute('aria-disabled', 'true');
            }
        });

        document.getElementById('submitLink').addEventListener('click', function(event) {
            if (this.classList.contains('disabled')) {
                event.preventDefault();
                alert('Form is not valid.');
            } else {
                alert('Form submitted.');
            }
        });
    </script>
</body>
</html>
output
JavaScript disable anchor – form validation example

Table of Methods and Use Cases

MethodDescriptionUse Case
preventDefault()Stops default event actionSimple link disabling
Disabled ClassUses CSS to visually and functionally disable a linkVisual indication needed
Wrapper FunctionWraps anchor in a function with conditionsConditional enabling or disabling

Best Practices for Disabling Anchors

  • Visual Indication: Make it clear that the link is disabled, use styles like color: gray.
  • Accessibility: Use attributes like aria-disabled to support screen readers.
  • Consistent Behavior: Ensure all disabled links behave similarly across your website.

Conclusion

How JavaScript disable anchor tags is now very clear to us. Any confusion? If yes, please write to us without any hesitation.

The preventDefault(), CSS classes, wrapper functions, or accessibility attributes – each method we have described with a working example from our side. In addition, we are requesting that you also follow our provided best practices in your upcoming JS projects whenever required.

Shawpnendu Bikash Maloroy
Shawpnendu Bikash Maloroy

๐Ÿ‹๏ธโ€โ™‚๏ธ Discover Code Blocks From 20+ yrs JS Expert
๐Ÿ’ฅ Asp.net C# Developer
๐Ÿ† Solution Architect
๐Ÿ‘จโ€โœˆ๏ธ Database Administrator
๐Ÿ“ข Speaker
๐ŸŽ“ MCTS since 2009

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Spread the love
ยซPrevious
Nextยป

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • 5 Lesser-Known JavaScript Functions
    5 Lesser-Known JavaScript Functions to Boost Your Coding Efficiency
  • 7 Weird JavaScript Tricks That Look Like Bugs
    7 Weird JavaScript Tricks That Look Like Bugs (#3 Will Shock You!)
  • Build a JavaScript Gamer Journal in 8 Lines
    ๐ŸŽฎ Build a JavaScript Gamer Journal in 8 Lines: Track Your Wins Like a Pro! ๐Ÿ†
  • JavaScript Pet Feeder Reminder in 7 Lines
    How to Code a Simple JavaScript Pet Feeder Reminder in 7 Lines: Feed Your Pet Like a Coding Boss! ๐Ÿถ
  • 10-line calculator JavaScript
    Build a Simple Calculator in JavaScript: 10 Lines to Wow Your Friends!

About-CodersTech Zone |  Contact |  Disclaimer |  Fact-Checking policy |  Affiliate Disclosure |  Privacy Policy

Copyright ยฉ 2024 CodersTechZone.com