JQuery event handler for child element triggers after parent when document.delegate used

393 Views Asked by At

I used the below html code for checking how the event bubbling works. I added the event handler for child element using $(document).delegate and for parent and super element I used HTML event attributes for handling click events. Generally when clicking on child element the event should gets bubbled from child to parent wise. Since I am using delegate for adding event in child element. When I click on child element the child alert gets triggered last after the parent and super gets triggered.

Could any body please help how to make the child to triggered first using $documet.delegate

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).delegate("#child", 'click', clickHandler);
function Superclick(event){
alert ("super");
}
function Parentclick(event){
    alert ("parent");
}
function clickHandler(e){
 alert("child");
}
</script>
</head>
<body>
<div style="width:500px;height:500px;background-color:red" id="super" onclick="Superclick(event)">
<div style="width:300px;height:300px;background-color:green" id="parent" onclick="Parentclick(event)">
<div style="width:250px; height:250px; background-color:yellow" id="child">
</div>
</div>
</div>
</body>
</html>
1

There are 1 best solutions below

0
On

There's nothing you can do to stop the child event being invoked last in this case as that is specifically how event delegation works. It relies on the event bubbling through the DOM from the event target to the parent where the delegated handler is bound.

Also note that delegate() is deprecated. You should use on() instead, however it won't make a difference in this example.

There may be workarounds you can use to retrieve the necessary parent elements from the child using DOM traversal in the single delegated event handler, however how that would be done and any benefits it has would depend on your specific use case.