Как переписать такой кусок код с Jquery на читый JS?

Рейтинг: 2Ответов: 2Опубликовано: 15.02.2023

Главное из кода, я хочу понять функционал исчезновения всех элементов, кроме одно, который в событии мыши. Как это можно переписать на JS?

codepen

$(".point").on("mouseenter", function () {
  $(this).closest(".point-wrap").addClass("open");
  $(this).closest(".point-wrap").siblings('.point-wrap').css('opacity', '0');
});

$(".point").on("mouseleave", function () {
  $(this).closest(".point-wrap").removeClass("open");
  $(this).closest(".point-wrap").siblings('.point-wrap').css('opacity', '1');
});

Ответы

▲ 1Принят

Коментарии в коде должны помочь примерно понять, что скрывается в методах jQuery:

// $(".point")
[...document.querySelectorAll('.point')]
  //.on("mouseenter", function () {
  .forEach((point) => { point.addEventListener('mouseenter', function() {
    // $(this).closest(".point-wrap").addClass("open");
    this.closest('.point-wrap').classList.add('open');
    // $(this).closest(".point-wrap").siblings('.point-wrap')
    [...this.closest('.point-wrap').parentElement.children].filter((el) => 
      (el.classList.contains('point-wrap') && el != this.closest('.point-wrap'))
    )
    // .css('opacity', '0');
    .forEach((wrap) => { wrap.style.opacity = '0'; });
  });
});
/* Чуть оптимизированный код ниже аналогичен предыдущему, 
   за исключением значения прозрачности и удаления класса */
[...document.querySelectorAll('.point')].forEach((point) => {
  point.addEventListener('mouseleave', function() {
    let parentWrap = this.closest('.point-wrap');
    parentWrap.classList.remove('open');
    [...parentWrap.parentElement.children].forEach((wrap) => {
      if (wrap.classList.contains('point-wrap') && wrap != parentWrap) wrap.style.opacity = '1';
    });
  });
});
*{box-sizing:border-box}body{display:flex;justify-content:center;align-items:center}.wrapper{position:relative;border:1px solid}img{height:400px;max-width:100%}ul{list-style:none;margin:0;padding:0}ul li{position:absolute;left:0;top:0;transition:.2s linear}ul li.open .point{background-color:#00bfff}ul li:first-child{top:10%;left:60%}ul li:nth-child(2){top:30%;left:40%}ul li:nth-child(3){top:15%;left:20%}ul li:nth-child(4){top:50%;left:80%}ul li:last-child{top:25%;left:70%}.point{cursor:pointer;width:30px;height:30px;border-radius:100%;background-color:#dc143c;transition:.4s ease-in}
<div class="wrapper">
  <img src="https://cakeshop.com.ua/images/6eRbfrsEzMM/h:1000/bG9jYWw/6Ly8vY2FrZXNob3AuY29tLnVhL3B1YmxpY19odG1sL3N0b3JhZ2UvYXBwL3B1YmxpYy9pbWcvcHJvZHVjdC85NDc0XzEuanBn" alt="Cat">
  <ul>
    <li class="point-wrap"><div class="point"></div></li>
    <li class="point-wrap"><div class="point"></div></li>
    <li class="point-wrap"><div class="point"></div></li>
    <li class="point-wrap"><div class="point"></div></li>
    <li class="point-wrap"><div class="point"></div></li>
  </ul>
</div>

▲ 1
let o=document.querySelectorAll("[class='point']");
let cnt=o.length;
for(i=0; i<cnt; i++){
o[i].addEventListener('mouseover',function(event){
  this.parentElement.className='point-wrap open';
  for(j=0;j<cnt;j++){
    if(o[j]!==this){
      o[j].parentElement.style.opacity='0';
    }
  }
});
};
for(i=0; i<cnt; i++){
o[i].addEventListener('mouseleave',function(event){
  this.parentElement.className='point-wrap';
    for(j=0;j<cnt;j++){
    if(o[j]!==this){
      o[j].parentElement.style.opacity='1';
    }
  }
});
};