How to Disable Link in JavaScript?

In this tutorial, I will tell you how to disable link using javascript. As there are many ways to disable hyperlink like we can use event handler, getelmentbyid and set attribute method which is used to get and set value, attribute on any  HTML element. So, following are the ways to stop the link functionality.

How to Disable Link in JavaScript?

Method 1: Using CSS

To disable hyperlink the main CSS property that we use is pointer events. Check the code given below.

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>
      Disable HTML href link using JS
    </title>
    <style>
      a.disabled {
        pointer-events: none;
      }
    </style>
  </head>

  <body style="text-align:center;">
    <h1 style="color:red;">
      Hello World
    </h1>
    <a href="http://thecrazyprogrammer.com/" id="linkId">
      LINK
    </a>
    <br /><br />
    <button onclick="disableLink()">
      disable  
    </button>
    <p id="linkStatus" style="color:green; font-size: 20px; font-weight: bold;"></p>
  </body>
</html>

<script>
                        let link = document.getElementById('linkId');
			let down = document.getElementById('linkStatus');
			function disableLink() {
			link.setAttribute('class', 'disabled');
			link.setAttribute('style', 'color: black;');
			down.innerHTML = 'Link disabled';
			}
</script>

Method 2: Using Function

<a href="http://thecrazyprogrammer.com/" id='TheLink'>test</a>
<input type='button' value="Disable" onclick="disableLink( 'TheLink', this );">

<script type="text/javascript">
  function disableLink(linkID, objButton) {
      const el = document.getElementById(linkID);
      if (!el.onclick) {
        el.onclick = function() {
          return false;
        };
        objButton.value = "Enable";
      } else {
        el.onclick = function() {
          return true;
        };
        objButton.value = "Disable";
      }
    }
</script>

Method 3: Using Event Handler

Event handler used to handle any action like inputting data, calling methods etc.

Example:

<a id="openSite" href="http://thecrazyprogrammer.com/">open website</a>
<button onclick=disablelink('openSite')>Disable link </button>

<style>
.disabledLink
{
color: #333;
text-decoration : none;
cursor: default;
}
</style>

<script>
function disablelink(linkID)
{
var hlink = document.getElementById(linkID);
if(!hlink)
return;
hlink.href = "#";
hlink.className = "disabledLink";
}
</script>

You can replace # (hash) with javascript:void (0) event handler.

Comment down below if you have queries or know any other way to disable hyperlink in javascript.

1 thought on “How to Disable Link in JavaScript?”

Leave a Comment

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