How to enable, disable links in jquery

This is very quick tutorial about enabling and disabling links in jquery, Some time in our web based project it requires at the some stage to enable disable links on any action or jquery event. Like if you want to process some data in background and need a solution to disable some links on page then below jquery code snippet is very useful for you.
Here i have created a simple html page with some anchor tags (links).

<a href="index.html?page=home" >Home</a> | 
<a href="index.html?page=about" >About Us</a> |
<a href="index.html?page=contact" >Contact Us</a>

These are the sample links, replace with your’s

Now at the end I added a disable, enable button to control above links behavior.

<button id="st">Disable</button>

Finally added jquery on page, don’t forget to add jquery library first. after that add below jquery code snippet.

$(function() {
   $("#st").click(function() {
   	  if($(this).text() == 'Disbale') {
   	  	$("#links a").addClass('disable');
        alert("All links has been disabled");
   	  } else {
        $("#links a").removeClass('disable');
        alert("All links has been enabled");
   $("#links a").click(function(e){
     if($(this).hasClass('disable')) {
       alert("Link disabled");

In the above code as soon as you click on the Disable links it adds disable class on all given links and it converts itself in Enable button

If you click on any link with disable class then it’ll show you error message like link is disable. I used jquery hasClass() function to check whether disable class added on link or not. If disable class added then it’ll prevent normal action of anchor tag using jquery e.preventDefault() method.



If you like this post please don’t forget to subscribe my public notebook for more useful stuff