Prevent onclick action with jQuery

jQuery is not going to solve this one OOTB. It can help, but none of stopPropagation, stopImmediatePropagation, preventDefault, return false will work if you simply attach them to the element. You need to override the element’s click handler.

However you state in your question “without removing onclick actions”. So you need to override the default behavior at the point the event is triggered, (as opposed to the cleaner approach of simply nulling out the onclick attribute for disabled anchors):

Here’s what I mean:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Disable clicks</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
</head>
<body>
  <a href="#" onclick="alert('panic!')">Let's panic</a>
  <a href="#" onclick="alert('panic!')" disabled="disabled">I can't panic no more</a>

  <script>
  $('a[onclick]').each(function(){
    $(this).data('onclick', this.onclick);

    this.onclick = function(event) {
      if($(this).attr('disabled')) { // HERE
        return false;
      };

      $(this).data('onclick').call(this, event || window.event);
    };
  });
  </script>
</body>
</html>

Demo here.

The approach there is to override the inline click handler (onclick) with preemptive logic to catch the case where the anchor is “disabled” and then cancel the event (with return false).

The benefit there is that to enable an anchor again you simply .removeAttr('disabled') on it.

Leave a Comment