Links are useful for navigating a website and why would anyone want to disable it, depends on a situation. I have seen this kind of behavior on bank portals. In such cases, you can simply remove the page link from the <a> tags href attribute. However, if you want to do this dynamically, on special occasions, try these examples.
Disable <a> tag in JavaScriptusing DOM addEventListener() Method
The DOM addEventListener() method attaches an event handler to the document. We can use this method to prevent a link from opening a page.
<html> <head> <title>Disable Link using JavaScript</title> </head> <body> <p>The below link is disabled using JavaScript</p> <a href='https://www.encodedna.com/' id='home' target='blank'>Home</a> </body> <script> var lnk = document.getElementById('home'); if (window.addEventListener) { document.addEventListener('click', function (e) { if (e.target.id === lnk.id) { e.preventDefault(); // Comment this line to enable the link tag again. } }); } </script> </html>
The addEventListener() method returns the element (e) when clicked anywhere on the document. When a user click’s our Home Link, the listener checks the id and prevents the <a> tags default behavior that is opening the specified link.
You can use the name attribute too. For example, if the hyperlink has a name attribute like,
<a href="https://www.encodedna.com/" name="theHomePage" target="blank">Home</a>
then your if condition should be,
if (e.target.name === 'home') { e.preventDefault(); }
If you want to disable multiple <a> tags or hyperlinks on a web page, you can simply use the nodeName property of the element, like this …
if (e.target.nodeName === 'A') { e.preventDefault(); }
👉 How to restrict or disable Browser back button using plain JavaScript
Using jQuery to disable <a> tag
With jQuery, you can use the click handler, which will return a false when someone clicks the link. Its like saying, do nothing when this link is clicked.
<html>
<head>
<title>Disable link tag using jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<p>The below link is disabled using jQuery</p>
<a href="https://www.encodedna.com/" id="home" target="blank">Home</a>
</body>
<script>
$(document).ready(function () {
$('#home').click(function () {
return false;
});
});
</script>
</html>
In the above example, I am using the id as selector. You can the a as selector when you want to disable all the links on a web page, like this.
$('a').click(function() {
return false;
});
As usual, the jQuery methods are less complicated and straightforward. However, if you want to avoid using a library, then I would recommend using the first example above that uses a simple JavaScript method.