Alex Rivera | Logout

Prevent onclick action with jQuery

Asked 2009-11-18T14:35:22.320
31

there are some links with onclick event actions

<a href="#" onclick="alert('panic!')">Let's panic</a>
<a href="#" onclick="alert('panic!')" disabled="disabled">I can't panic no more</a>

I need prevent event actons execution on links with disabled attribute without removing onclick actions.

$('a[disabled]').click(function(e){
  e.stopPropagation();
  return false;
});

This code doesn't helps me.

update Even this code doesn't work

<html><head><script type='text/javascript' src='jquery-1.3.2.js'></script></head>
<body>
<a href='#' onclick="alert('HA-ha!')" disabled="disabled" class="disabled">TEST</a>
<script type="text/javascript">
    $('a[disabled], a.disabled').click(function(e){
        console.log('override?');
        e.stopImmediatePropagation();           
            e.preventDefault();
        e.stopPropagation();
        return false;       
    });
</script>
</body></html>
Edit
Report

1 Answer

6

The problem is that jQuery adds events in order. To stop other events, the events you need to stop must come after your stopping code. Since you have code in your on click, you will need to change up the order. This is what I would do:

<a href='#' onclick="alert('HA-ha!')" class="disabled">TEST</a>
<a href='#' onclick="alert('HA-ha!')">TEST</a>
<script type="text/javascript">
    $('a').each(function(){
        // Cache event
        var existing_event = this.onclick;

        // Remove the event from the link
        this.onclick = null;

        // Add a check in for the class disabled
        $(this).click(function(e){ 
            if($(this).hasClass('disabled')){
                e.stopImmediatePropagation();
                e.preventDefault();
            }                
        });

        // Reattach your original onclick, but now in the correct order
        // if it was set in the first place
        if(existing_event) $(this).click(existing_event);
    });
</script>

The benefit is just remove/add the disabled class using jQuery: $('a#whatever').addClass('disabled') or remove it $('a#whatever').removeClass('disabled') and no other cleanup/setup is required.

answered 2009-11-18T15:16:07.940

Your Answer