Search code examples
javascriptstoppropagation

How to use event.stopPropagation() JavaScript


I have three elements with events assigned to them. How should I use event.stopPropagation so only events for elements #1 and #2 are executed, but not for #3? I put event.stopPropagation in element #2 as it stops bubbling. In my understanding, it should stop the triggering of the event in #3 but it doesn't seem to be working, all events are still being executed. Here is JS code:

    document.addEventListener("DOMContentLoaded", function() {
      document.querySelector('#element1').addEventListener('click', function(e) {
        console.log('Event in #element1 fired!');
      });

      document.querySelector('#element2').addEventListener('click', function(e) {
        event.stopPropagation();
        console.log('Event in #element2 fired!');
      });

      document.querySelector('#element3').addEventListener('click', function(e) {
        console.log('Event in #element3 fired!');
      });
    });
<div id="element3" class="element">
  Element 3
  <div id="element2" class="element">
    Element 2
    <div id="element1" class="element">
      Element 1
    </div>
  </div>
</div>


Solution

  • This line is wrong:

    event.stopPropagation();
    

    because the parameter with the event object passed to the function is named e.

    You need to write this as:

    e.stopPropagation();