I am attempting to unbind all events attached to elements inside a container using JQuery’s off function however it is doing some odd things.
My code is as follows
<div id='container'>
<button id='test_btn'>Test</button>
<button id='live_btn_id1'>Action</button>
<button id='live_btn_id2'>Action</button>
</div>
$("#test_btn").on("click", function(){
$("#container").find("*").off();
});
$("#container").on('click', 'button[id^=live_btn]', function(event) {
alert("hello");
});
The result of this is that the test_btn correctly stops working however the ‘Action’ buttons continue to work. However if I do the following:
$("#container").off();
It works as expected but that also removes my stuff I have attached to container. Is there a reason for this odd behaviour?
When you use delegation you are binding to the element, not the descendant selector.
So you call
$("#container").on(...and you are binding to#container, notlive_btn..offonlive_btnwould not make sense because nothing is bound to them.A possible solution is to namespace the click event: