views:

24

answers:

3

As many browsers do not show tooltips on disabled form elements (as Opera does), I decided to emulate disabled button with jQuery.

When disabling I just set control's class to disabled and for buttons/submit controls I add an event handler click(function(){return false;}) and I can unbind it later when reenabling the control.

Now the problem is - I need to remove all attached event handlers (click, enter key) from the disabled control, except 'mouseenter' and 'mouseleave' because I am using a custom jQuery based tooltip which needs those events. And after re enabling the button, I need to restore all handlers back.

I know that I can store the attached event handlers in $.data() but I have no idea, how to gather all the event handlers except 'mouseenter' and 'mouseleave'.

Can you help me?

+1  A: 

unbind - http://api.jquery.com/unbind/

Māris Kiseļovs
+1  A: 

try this:

<script>

$(function() {

//Lets attach 2 event handlers to the div
$("#el").click(function(){ alert("click"); });
$("#el").mouseover(function(){ alert("mouseover"); });


//We iterate on the div node and find the events attached to it

$.each($("#el").data("events"), function(i, event) {
    output(i);
    $.each(event, function(j, h) {
      output(h.handler);
      //DO your unbind here if its not a mouse-enter or a mouseleave
    });
  });
});

function output(text) {
    $("#output").html(function(i, h) {
        return h + text + "<br />";
    });
}

</script>

<div id="el" style="width: 200px; height: 200px; border: solid 1px red;">Test</div>
<span id="output"></output>
Nands
Thanks, your code together with event.type analysis did the trick.
Martin
+1  A: 

I wouldn't go to all that work.

Since you have a .disabled class on the disabled elements, I'd just use that as a flag to disabled/enable the functionality by testing for that class in an if() statement, and returning false if the element has the disabled class.

So using the click handler you gave, instead of:

$('someElement').click(function(){return false;});

I'd do this:

$('someElement').click(function() {
    if( $(this).hasClass( 'disabled' ) ) {
        return false;
    } else {
        // run your code
    }
});

Now when you remove the .disabled class, the input will work again. No unbind/bind or tracing using .data(). Much simpler.

patrick dw
Yes, this would be the most efficient solution, but it will force other developers who might write some event handlers, to remember to check for disabled status. I would like the enabler/disabler solution to be like some separate piece of code, most probably, jQuery plugin.
Martin