15

I want to check if an element is scrolled to top with an offset of ~ 100px.

I´ve got a page with 5 subcontents and 2 classes to make backgrounds. It looks like this:

<div class="background1">
Content1
</div>
<div class="background2">
Content2
</div>
<div class="background1">
Content3
</div>
<div class="background2">
Content4
</div>
<div class="background1">
Content5
</div>

Now i want to check, when one of these classes reaches the top by scrolling

This is one of my last trys:

$('.background1', '.background2').position(function(){
             if($(this).position().top == 100){
            alert('checkThis');
        }
        }); 

I think this is my closest try by now...of course this code is in document.ready and at the end of my code....

TLDR: How to check if an element got scrolled to top (and some offset)?

Top Questions
  • 1,862
  • 4
  • 26
  • 38

1 Answers1

29

You have to listen for the scroll event, then check each element against the currently scrolled distance, something like :

$(window).on('scroll', function() {
    var scrollTop = $(this).scrollTop();

    $('.background1, .background2').each(function() {
        var topDistance = $(this).offset().top;

        if ( (topDistance+100) < scrollTop ) {
            alert( $(this).text() + ' was scrolled to the top' );
        }
    });
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • This lloks about what i searched for...I totally fixed on that how to get the position...but forgot the scroll to get there...thanks! Accept in 8 minutes. – Top Questions Sep 23 '13 at 14:02
  • 2
    `position()` gets the elements position relative to the parent, I'm betting you're looking for `offset()`, which gets the position relative to the document. Also note the selector, as your selector looks for `.background1` inside `.background2`, and does not select both. – adeneo Sep 23 '13 at 14:03
  • Awesome! This line: `var scrollTop = $(this).scrollTop();` was exactly what I was looking for. I couldn't figure out why the .offset().top value wasn't changing at all. Now I see that the offset value is related to document, so it's permanent -- that's why you need to compare it to the `$(window).scrollTop()` value. – rgb_life Oct 20 '17 at 11:19