I have a div with an id of registerModal
. I wanted to disable all 'click' event inside the div's. For example I have the following:
<a id="instagram-login-btn" class="inst-btn" href="">
</a>
and the following:
$('#instagram-login-btn').on('click', function (event) {
});
I tried doing:
$('#registerModal').off('click', '**');
but this didn't work out. Any other way to disable all clicks on a child elements div?
I have a div with an id of registerModal
. I wanted to disable all 'click' event inside the div's. For example I have the following:
<a id="instagram-login-btn" class="inst-btn" href="">
</a>
and the following:
$('#instagram-login-btn').on('click', function (event) {
});
I tried doing:
$('#registerModal').off('click', '**');
but this didn't work out. Any other way to disable all clicks on a child elements div?
Share Improve this question asked Oct 14, 2013 at 2:59 aditadit 33.7k72 gold badges235 silver badges380 bronze badges 1- possible duplicate of How to remove all event handlers for child elements of a parent element using JQuery – j08691 Commented Oct 14, 2013 at 3:01
3 Answers
Reset to default 4Use event delegation which is disabled by the presence of a class.
var modal = $('#registerModal');
modal.on('click', "#instagram-login-btn:not(.disabled)", function(event) {
// the handler
});
modal.on("click", "#another_element:not(.disabled)", function(event) {
// the handler
});
Then to disable them, add the disabled
class.
$("#registerModal *").addClass("disabled");
And remove the class to enable.
$("#registerModal *").removeClass("disabled");
These are adding/removing the class on all nested elements, but your actual code can be more targeted.
Another way to do it without classes is to bind handlers that stop the propagation of the event to the nested elements.
var modal = $('#registerModal');
modal.on('click', "#instagram-login-btn", function(event) {
// the handler
});
modal.on("click", "#another_element", function(event) {
// the handler
});
Then to disable them, stop the bubbling with a handler
$("#registerModal *").on("click", function(event) { event.stopPropagation() });
And remove the handler to enable.
$("#registerModal *").off("click");
Again, the selection should be targeted toward the actual desired elements.
Try
$('#registerModal').find('*').addBack().off('click',);
To set each one, and verify, I always do it in a loop. Such as the following:
$('#registerModal').find("*").each(function(i,e)
{
$(this).unbind("click");
});
All answer are pragmatically correct, but I have tend to notice more stable behavior with multiple event handling using the $.each for it.