I have the following span
on a page with several click event handlers:
<span class="abc">xyz</span>
Now I need to stop bubbling up of its click event. It can be achieved in two ways:
Add stopPropagation
in one of the click handlers: (Child-2 in fiddle)
$(document).on("click", ".abc", function (e) {
e.stopPropagation();
});
All the click handlers of the span are being called in this case and none of the parent handlers are being called which is ideal behavior.
Add an onclick
property like following:(Child-1 in fiddle)
<span class="abc" onclick="event.stopPropagation()">xyz</span>
In this case, none of the click handlers are being called (neither child span nor parent).
Can someone please explain why the click handlers of child span are not being called in second case?
Fiddle:
$(document).on("click", ".abc", function (e) {
alert("child click!");
e.stopPropagation();
});
$(document).on("click", "#parent", function () {
alert("parent click!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="parent">
<span class="abc" onclick="event.stopPropagation()">Child-1!</span>
<br />
<span class="abc">Child-2!</span>
</span>
You're not seeing a click when you use the onclick
attribute because the click never reaches document
— because you stopped propagation.
You're using event delegation:
$(document).on("click", ".abc", function (e) {
// ---------------------^^^^^^^
alert("child click!");
e.stopPropagation();
});
$(document).on("click", "#parent", function () {
// ---------------------^^^^^^^^^^
alert("parent click!");
});
That means you're really hooking the handler on document
. If the click never bubbles to document, jQuery can't fire your delegated handlers.