R
R
RushV2021-06-27 10:45:12
JavaScript
RushV, 2021-06-27 10:45:12

What is the right way to implement such JS code?

Hello!
How to check block visibility on scroll?
If the div block came into view, then display it.

$(window).scroll(function () {
         if ($('.row').is(':visible')) {
            alert("ок")
        }
     });

Am I doing it right, or is this not how it's done?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
y0u, 2021-06-27
@RushV

const onIntersection = (entries) => {
  entries.forEach(entry => {
    if (entry.intersectionRatio > 0) {
      // visible
    } else {
      // not visible
    }
  });
};

const observer = new IntersectionObserver(onIntersection);
observer.observe(document.querySelector('#element'));

Example: https://jsfiddle.net/8craw2nt/
Docs: https://developer.mozilla.org/ru/docs/Web/API/Inte...
Browser compatibility: https://caniuse.com/intersectionobserver

J
jamtuson, 2021-06-27
@jamtuson

It is necessary to get the coordinates of the block and look at the position of the user's scroll.
Then simply:

if(координаты блока - координаты пользователя === отступ видимости) {
  //сделать что - то
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question