0

There are multiple div in my page. How could I detect, that any of the div is visible for the first time when the page is being scrolled down.

I was trying something like:

$('div').offset().top() < $(window).scrollTop()

but surely it won't work. What is the best way to handle this?

1 Answers1

1

Going off the first part of the answer: when something comes into view. https://stackoverflow.com/a/22480938/825240

function isScrolledIntoView(el) {
    var elemTop = el.getBoundingClientRect().top;
    var elemBottom = el.getBoundingClientRect().bottom;

    var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
    return isVisible;
}

This is the first step.

Now we need to have a way to see if a div has been viewed before.

var divWeCareAbout = document.getElementById("someDiv");

window.addEventListener("scroll", function(){
    if(isScrolledIntoView(divWeCareAbout)){
        if(!div.dataset.haveSeen){
            //The div had scrolled into view and 
            //this is the first we have seen of it.
            //Do whatever here.
            div.dataset.haveSeen = true;
        }
    }
});
Community
  • 1
  • 1
powerc9000
  • 2,030
  • 19
  • 30