How to pass this Jquery code in pure Javascript

Asked

Viewed 38 times

0

$(".checkbox-menu").on("change", "input[type='checkbox']", function() {
   $(this).closest("li").toggleClass("active", this.checked);
});

$(document).on('click', '.allow-focus', function (e) {
  e.stopPropagation();
});

1 answer

1

Can use document.addEventListener checking with event.target which element was clicked (click) or modified (change) (the event is the first argument of callback, where I can give any name. In case I put only e):

document.addEventListener("change", function(e){
   var el = e.target; // elemento alterado
   if(el.closest(".checkbox-menu")){ // verifico se ele está dentro da classe
      el.closest("li").classList.toggle("active", this.checked);
   }
});

document.addEventListener("click", function(e){
   var el = e.target;
   // aqui eu verifico se o elemento clicado é filho de .allow-focus
   // inclusive os nós de texto, ou o próprio .allow-focus
   if(el.classList.contains("allow-focus") || el.closest(".allow-focus")){
      console.log(".allow-focus clicado");
      e.stopPropagation();
   }
});
.active{
   color: red;
}

.allow-focus{
   background: red;
}
<ul class="checkbox-menu">
   <li>
      <input type="checkbox"> Item 1
   </li>
   <li>
      <input type="checkbox"> Item 2
   </li>
</ul>
<span class="allow-focus">
   <input type="checkbox"> clique aqui
   <br>
    clique aqui também, ou em qualquer área vermelha
</span>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.