Home » Jquery » javascript – Refactor jQuery inview event listener-Exceptionshub

javascript – Refactor jQuery inview event listener-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

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?

How to&Answer:

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>

Answer:

Except the event you can use this:

(function() {
     document.querySelector("h2, .single").addEventListener("click", function(){
         this.classList.add("is-show");
  });
})();

I didn’t find an equivalent for inview. You can refer to this.