Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override a parent event listener when a child element is clicked in Javascript?

How do I override aFunction inside of child.js?

I want the child event listener to trigger without aFunction triggering, and I can't modify parent.js.

Is this even possible?

index.html:

       <th class="foo">foo &nbsp;&nbsp;

            <span class="bar" data-feather="arrow-down"></span>

        </th>

parent.js:

       parent = {
            init: function() {
                parent.aFunction($('.foo'));
            },
            aFunction: function(element) {
                element.on('click', function() {
                    alert('foo');
                });
            }, ...

         window.onload = parent.init;

child.js:

    $('.bar').on('click', function() {
      alert('bar');
    });
like image 748
Lord Elrond Avatar asked Oct 26 '25 07:10

Lord Elrond


1 Answers

  • First its .bar cause no html tags called bar
  • event.stopPropagation() Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

Example

$('.foo').on('click', function() {
  alert('foo');
});
$('.bar').on('click', function(e) {
  e.stopPropagation();
  alert('bar');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foo">foo &nbsp;&nbsp;
    <span class="bar" data-feather="arrow-down">Bar</span>
</div>
like image 104
Mohamed-Yousef Avatar answered Oct 28 '25 22:10

Mohamed-Yousef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!