Avisek Chakraborty
Avisek Chakraborty

Reputation: 8309

How to restrict event stopPropagation upto an ancestor element?

Is it possible to stop propagation upto a certain ancestor-element!

However we can do it- by adding the event.stopPropagation() in the parent itself, for that event, but that might block certain cases.

Upvotes: 0

Views: 184

Answers (1)

Kristjan Kiolein
Kristjan Kiolein

Reputation: 103

You can check the target of the event and stop only those that came from the element that you wish to stop the propagation for.
(If you use jquery, it can be done more easily. Don't know better way with js.)

if(event.target == document.getElementById('elementToBlock')) event.stopPropagation();

This way other events still propagate.
If you have lot of elements and you don't want to add a common class to them you can also group them in div and stop all events propagating from there.
Made a sample with jquery :

$('#dontPropagateThroughHere').on('click', '.dontPropagate', function(event) {
  event.stopPropagation();
  alert('Stopped by dontPropagateThroughHere');
})

$('#propagationBlocker').on('click', function(event) {
  event.stopPropagation();
  alert('Stopped by propagationBlocker');
})

$('#eventsThatGotThrough').on('click', function(event) {
  alert('Event got through');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='eventsThatGotThrough'>
  <div id="dontPropagateThroughHere">
    <div id="propagationBlocker">
      <div>Don't propagate inside blokker div</div>
      <div>Don't propagate inside blokker div</div>
      <div>Don't propagate inside blokker div</div>
    </div>
    <br/>
    <div class="dontPropagate">Don't propagate</div>
    <div class="dontPropagate">Don't propagate</div>
    <div class="dontPropagate">Don't propagate</div>
    <br/>
    <div>Let me propagate</div>
    <div>Let me propagate</div>
    <div>Let me propagate</div>

  </div>
</div>

Upvotes: 1

Related Questions