Thursday, September 3, 2009

Onclick link disabling with jQuery


Days back I have come across a common requirement to disable link on clicking it once. Typically, it's because on click of those links some AJAX thins happen and some fragments of the page gets updated.

I had those sort of links across screens and I have written Javascript using jQuery as 'Unobtrusive Javascript'. All I gotta do is to add a class called 'j_link_to_disable' to the links I wanted to disable. As class name of the element is supposed to be used to specify style the prefix 'j_' differentiates from javascript used class names.

<html>
  <head>
    <title>Link disabling test</title>
    <script type="text/javascript" src="http://jqueryui.com/latest/jquery-1.3.2.js"></script>
  </head>
                                           
  <body>
 
   <p><a href="#" id="vanish_link_id" class="link_to_disable">Some link to disable</a></p>
   <p><a href="#" id="vanish_link_id" class="link_to_disable">Another link to disable</a></p>
   <p><a href="#" id="vanish_link_id">Some link NOT to disable</a></p>


    <script type="text/javascript">
	$($('.link_to_disable').click(
      	 function disableLink(){
	        link =  $("#vanish_link_id");       
      	  link.after('<p>'+link.text()+'</p>').remove();
		 event.preventDefault();
       }));
    </script>

  </body>                               
</html>

No comments:

Post a Comment