How to Disable HyperLink using Jquery -3 Techniques

In this post I will discuss various approaches to disable a Hyperlink with Jquery.  More specifically, I will be covering 3 approaches

 

  1. Disable Links by utilizing preventDefault
  2. Disable Links by Removing the href attribute
  3. Disable Links by utilizing the click handler

Lets start

 

1) Disable link by utilizing preventDefault()

 If this method is called, the default action of the event will not be triggered. (official documentation). In case of hyperlink , the default behavior is to open a new page in browser.  Using preventDefault will remove this behavior.
Here is the basic code snippet. In this snippet we are calling the prevent default method on the element with class spice-link. We can also disable all links in a document by attaching prevent default to the <a> element. .
<head>
 <meta charset="utf-8">
 <title>jQuery UI Datepicker - Display multiple months</title>
 <script src="//code.jquery.com/jquery-1.10.2.js"></script>
 <script>
 
 $(function() {
 
$('.spice-link').click(function(e) { e.preventDefault(); });
// disable all links in a document
$('a').click(function(e){e.preventDefault();});

});

</script>
</head>
<body>
<a href = "http://spiceforms.com" class = "spice-link"> Click Here</a>
</body>

 

2) Remove the Href attribute

Another way to disable a hyperlink is to simply remove the href attribute. We can do so by using the  .removeAttr() function.  Take note that since we are removing  href, the link will appear as a normal text. You might want to add additional CSS classes so that the element appear as a link. Here is the snippet
<head>
 <meta charset="utf-8">
 <title>jQuery UI Datepicker - Display multiple months</title>
 <script src="//code.jquery.com/jquery-1.10.2.js"></script>
 <script>
 
 $(function() {
 
$('.spice-link').removeAttr("href");
// disable all links in a document
$('a').removeAttr("href"); 

});

</script>
</head>
<body>
<a href = "http://spiceforms.com" class = "spice-link"> Click Here</a>
</body>

 

3) Utilize Click Handler:

The .click() function allows us to bind a custom handler to the click event (documentation). So in order to disable a hyperlink, we will add a handler and simply return false. Here is the snippet.
<head>
 <meta charset="utf-8">
 <title>jQuery UI Datepicker - Display multiple months</title>
 <script src="//code.jquery.com/jquery-1.10.2.js"></script>
 <script>
 
 $(function() {
 
$('.spice-link').click (function () {

return false; 
});
});

</script>
</head>
<body>
<a href = "http://spiceforms.com" class = "spice-link"> Click Here</a>
</body>

 

Conclusion

Well Jquery really make DOM Manipulation a piece of cake. There are quite a few more ways to disable links with Jquery.  If you have something to share then let us know in the comments.
This post is inspired by this discussion 
About Ankit

Founder of Spice Forms.
Spice Form is a Drag n Drop tool to create powerful web forms in minutes.

Speak Your Mind

*