How to know when an element is at the top of the page

1

I'm developing a one page website with several sections (about, contact, services for example)

And a fixed menu, the idea is as the user scrolls the page the fixed menu would change the active links, ie when in the contact section, in the fixed menu the contact link would become "active"

My question is, how do I know when the section went through the top of the page, so I could remove the links as active, obs: I use jquery.

If you are interested, this is the site link

    
asked by anonymous 25.05.2017 / 13:51

2 answers

2

You need to check the position of the scroll in each action - scrolling. Then:

$(window).scroll(function () {
   var divAtiva;
   $.each($("#conteudo .div-interna"), function (indice, obj) {
      if (!divAtiva || ($(this).scrollTop() >= $(obj).offset().top * 0.80 && divAtiva.top < $(obj).offset().top * 0.80))
         divAtiva = { elementId: $(obj).attr("id"), top: $(obj).offset().top };
  });
  MetodoQueSelecionaOMenu(divAtiva);
});

Assuming its structure looks something like:

<div id="conteudo">
<div class="div-interna" id="div1">...</div>
<div class="div-interna" id="div2">...</div>
<div class="div-interna" id="div3">...</div>
</div>

I took into consideration that you would like to select the active div when scrolling reaches 80% of your top, okay? Otherwise, just change the calculation here: $(obj).offset().top * 0.80 to whatever value you want. (=

    
25.05.2017 / 14:26
2
    $(window).scroll(function() {
        //Altura atual do scroll
        var tamScroll = $(this).scrollTop();

        //Altura para disparar ação
        if(tamScroll >= 50)
        {
            //Loop para section
            $('.screen').each(function(i) {
                //verifica altura da section
                if ($(this).position().top <= tamScroll - 50) {
                    //Se satisfaz a condição, remove o link atual
                    $('nav a.active').removeClass('active');
                    //Adiciona classe no novo link da section atual
                    $('nav a').eq(i).addClass('active');
                }
            });
        }
        else
        {
            //Caso não satisfaça condição principal, a página está no topo.
            $('nav a.active').removeClass('active');
            $('nav a:first').addClass('active');
        }

    });
    
25.05.2017 / 14:18