2

I have event handler bound to every element of the page via $(document).bind().

Does anybody know how to unbind this handler for particular element?

Here is my sample code that doesn't work the way I want:

<html><head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js">    </script>
</head>
<body>
    <div id="mid" style="cursor:pointer" >click me</div>
    <div>sample</div>
    <script type="text/javascript">
        var fun = function() {
            alert('default handler');
        };
        $(document).bind('click.custom', fun);
        //trying to unbind the handler but it remains there
        $("#mid").unbind('click.custom');
    </script>
</body>
</html>

Considering Daniel's answer here is this problem again:

var ff = function() {
    alert('additional');
}

$(document).bind('click.custom', fun);
$(document).bind('click.custom2', ff);
$("#mid").bind('click.custom', false); 

here fun event handler was perfectly unbound from #mid element, but ff event handler was unbound also and that is a problem for me.

exodus
  • 21
  • 3

2 Answers2

1

Its called event bubbling. The events of the nested elements go up to the parents.

You should bind to #mid and return false from that handler.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • Well it works nice, thanks. But returning false from handler resets handlers in other namespaces. Is there any way to unbind only handler from particular namespace and left other handlers untouched? – exodus Mar 16 '11 at 00:35
0

There is only a single event bound to the document. Because of bubbling, the event will be sent up the DOM hierarchy until its propagation is stopped, or it reaches the document.

You could either modify the callback to ignore this event if it came from #mid, or use the in-built delegate/live to achieve the same effect.

$(document).delegate('[id!="mid"]', 'click.custom', fun);

This will ignore events coming from an element having the id "mid". Another alternate is to modify the function itself.

function fun() {
    if (this.id == "mid") { 
        return; // if event came from #mid, ignore it.
    }
    // continue processing as normal
}
Community
  • 1
  • 1
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • Modifying the callback function is right way to get desired result, I thought about it, but for my project I dont have permissions to modify either initial binding process or callback function. And it makes things really tough. But all your answers are perfect valid for my original question, so thanks guys. – exodus Mar 16 '11 at 01:03
  • If you don't have control over the event creation process, you could get hold of the original event handler function from jQuery, wrap it inside an outer function. Then your logic to ignore certain elements in this outer function. As far as jQuery knows, nothing changed. – Anurag Mar 16 '11 at 01:05