Refactor jQuery inview event listener

Striker :

I want to convert the following code to pure JavaScript.

$(function () {
    $('h2,.single').on('inview', function () {
        $(this).addClass('is-show');
    });
});

I tried much time but still can not figure out how. Any helps?

JHeth :

Inview was an old plugin to solve a problem that now has a web API, as long as you don't need to support IE you can use intersection observer to do this.

Without any example or further explanation of how you need things to function it's hard to guess what you want to achieve. But here's a basic implementation that would mimic the tiny bit of JQuery you provided.

const sections = [].slice.call(document.querySelectorAll(".single"));

function createObserver(el) {
  let observer;

  const options = {
    root: null,
    rootMargin: "0px",
    threshold: 0.5
  };

  observer = new IntersectionObserver(handleIntersect, options);
  observer.observe(el);
}

function handleIntersect(entries, observer) {
  entries.forEach((entry) => {
    let box = entry.target;
    let visible = entry.intersectionRatio;
    if(visible > 0.5) {
      box.classList.add('is-show');
    } else {
      box.classList.remove('is-show');
    }
  });
}



const setup = (sections) => {
  for (let i in sections) {
    const el = sections[i];
    createObserver(el);
  }
}


setup(sections);
.single {
  padding: 2rem;
  background: tomato;
  color: #fff;
  margin: 600px 0;
  transition: all .5s ease-out;
  opacity: 0;
}
.is-show {
  opacity: 1
}
<h2 class="single">I'm an H2 Element in frame</h2>
<h2 class="single">I'm an H2 Element in frame</h2>
<h2 class="single">I'm an H2 Element in frame</h2>
<h2 class="single">I'm an H2 Element in frame</h2>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11948&siteId=1