Home > Net >  JQuery event delegation in vanilla js
JQuery event delegation in vanilla js

Time:06-23

I have a strange situation I ran into with event delegation, the reason being the element is dynamically added to the DOM. A button is clicked to open the modal

To quickly explain this code, there is a modal drawer for desk and mobile and both are being selected here, and the click event is attached to the color swatches inside both of the modals. The modals are dynamically added to the DOM with js

Now the part that is tripping me up is currentTarget is document and if I use e.target, this will be the button that is clicked to open the modal in the first place.

In order to open the modal a button has to be clicked, therefore with event delegation the currentTarget is the document and the target is the button itself, so I really don't know how to attach the event listener to the .swatch in the modal.

$(document).on('click', '.modal-desk__content .swatch, .modal-mobile__content .swatch', e => {
   const $swatch = $(e.currentTarget);
   $('.product-form').find('.swatch[data-value="'   $swatch.data('value')   '"]').click();
   $swatch.closest('.swatches').find('.swatch').removeClass('selected');
   $swatch.addClass('selected');
})

CodePudding user response:

You could always attach the event listener to document on page load then just look for the appropriate class on click.

document.addEventListener("click",function(e){
     if(e.target.classList.contains("swatch")){
          console.log("swatched!");
     }
});

let b = document.createElement("button");
b.innerHTML = "TEST";
b.className = "swatch";
document.body.appendChild(b);

CodePudding user response:

I was thinking about this all wrong and overthought it. Here is the refactored version for anyone else that runs into this issue

document.addEventListener('click', e => {
   if (e.target.closest('.swatch')) {
      const $swatch = e.target.closest('.swatch')
      document.querySelector(`.product-form .swatch[data-value="${$swatch.dataset.value}"]`).click()

      $swatch.closest('.swatches .swatch').classList.remove('selected')
      $swatch.classList.add('selected')
   }
})
  • Related