Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event delegate binding in javascript

My task is to convert all jquery code to es6 compatible code.

Example:

  • Jquery

    $('.class1 .class2').on('click', function(e) {
         // logic here
    }
    
  • ES6 Compatible

    const test = document.querySelector('.class1 .class2');
    test.addEventListener('click', (e) => {
    //logic here
    });
    

This works fine, but I am unable to convert dom click events which are registered later.

Example:

  • Jquery

    $(document).on('click', '.class1 .pagination a', 
        function(e) {
         //logic here
    })
    

What I am trying to do :

var classname = document.querySelectorAll(".class1 .pagination a");

Array.from(classname).forEach(function(element) {
  element.addEventListener('click', (e)=>{
    e.preventDefault();
    alert(e);
  });
});

Here class .class1 .pagination a is registered later so classname is getting empty . But using jquery $(document).on('click', '.class1 .pagination a') it is working correctly.

Any pointer on how to convert $(document).on('click', '.class1 .pagination a') like events to es6 ?

like image 628
Aditya Avatar asked Sep 17 '26 06:09

Aditya


1 Answers

You can use event delegation by checking the event target using Element.matches():

const delegate = (container, evtType, targets, cb) => {
  const cont = (container === document || container instanceof HTMLElement) ?
    container : document.querySelector(container);

  if (!container) throw new Error('Event container not found');

  document.addEventListener(evtType, e => {
    if (!e.target.matches(targets)) return;

    cb(e);
  });
}

delegate(document, 'click', 'span, .class, #id, .container .inner a', (e) => console.log(e.target.innerText));
<div class="class">A class</div>
<div id="id">An id</div>
<span>An element</span>
<div class="container">
  <div class="inner"> <a href="#">Nested Selectors</a></div>
</div>

<div>Not delegated</div>
like image 90
Ori Drori Avatar answered Sep 19 '26 19:09

Ori Drori



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!