Event handling in javascript?

What is the main purpose of event bubbling and event capturing in javascript?

Hey @itzbrinth,

We have a great article on that over on the main site: https://www.sitepoint.com/event-bubbling-javascript/

If you have any questions, feel free to come back and follow up here!

Everything is ok but when i want to click an element i will get that by id or class and add a handler to it.What the real need for bubbling.

Bubbling is the default event capture that it used. It allows you to have an event handler on a container or parent element, so that you can easily catch all relevant events that occur inside of it without needing to add event handlers on to everything in there.

Will you give me a little example?

Sure thing.

<div class="links">
  <a href="#link1">Link 1</a>
  <a href="#link2">Link 2</a>
  <a href="#link3">Link 3</a>
</div>
function linksEventHandler(evt) {
  var link = evt.target;
  evt.preventDefault();
  doStuffWithLink(link);
}
var links = document.querySelector(".links");
links.addEventListener("click", linksEventHandler);
1 Like
  This is my code for event bubbling.How i can achieve event capturing in this code? 
 <div class="aone">
<p>i'm a</p>
    <div class="btwo">
      <p>i'm b</p>
       <div class="cthree">
          <p>i'm c</p>
                         <span>me</span>
       </div>
    </div>

  </div>
        
  
  var elementa=document.querySelector(".aone");

  // var elementa = document.getElementsByClassName('aone');
  console.log(elementa);

  elementa.addEventListener('click',handler);
  
  function handler(){
    alert('A called');
  }
  
  var elementb=document.querySelector(".btwo");
  
  elementb.addEventListener('click',function(){
    alert('B called');
  });
  
  var elementc=document.querySelector(".cthree");
  
  elementc.addEventListener('click',function(){
    alert('C called');
  });
  
  var elementspan=document.querySelector('span')
  
  elementspan.addEventListener('click',function(e){
    // e.stopPropagation();
    alert('span called');
  


});


you set the appropriate parameter in addEventListener().

Capturing occurs when you give true as the third argument to addEventListener, and only triggers from that one element. Nothing that occurs inside of that element will trigger the event.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.