LASH
LASH

Reputation: 126

How to detect when an element scrolled at the top of a page in jquery?

I am going to create a timeline for a website, something like Google timeline, I have some divs with the name of years with a class separator and when I scrolled up and reached a div at the top of page the year title at the left side should be changed to other year.

This is my HTML structure (just for example):

<div class="separator" data-year="2015">
  <!--Something Here-->
</div>

<div class="separator" data-year="2014">
  <!--Something Here-->
</div>

<div class="separator" data-year="2013">
  <!--Something Here-->
</div>


<div class="separator" data-year="2012">
  <!--Something Here-->
</div>

What should be my jquery code, and what functions should I use?

Upvotes: 0

Views: 108

Answers (1)

Bal&#225;zs Varga
Bal&#225;zs Varga

Reputation: 1856

Here's a very basic fiddle on what you can do: http://jsfiddle.net/atq0sh6y/

The jQuery code:

$(document).scroll(function(){
    $('.separator').each(function(){
        var top = $(window).scrollTop();
        var off = $(this).offset();
        if(top>off.top) {
            $('.header').text($(this).data('year'));
        }
    });
});

Hope it helps.

Upvotes: 2

Related Questions