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

Asked

Viewed 1,164 times

0

I am 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 it was in the contact section, in the fixed menu the contact link was "active"

My doubt is, how to know when the section went through the top of the page, so I could remove the putting links as active, Obs: I use jquery.

If you are interested this is the site http://mkmseguranca.com.br/

  • 1

    I think you already have several questions related to this, search in Stackoverflow, you will find! One of them here: https://answall.com/questions/4100/como-fixar-um-menu-horizontal-no-topo-da-janela-ao-rolar-a-p%C3%A1gina

  • @Douglasgarrido I’ll take a look

2 answers

1

    $(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');
        }

    });

1


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

$(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);
});

Supposing its structure is something similar to:

<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 it into consideration that you would like to select the active div when the scrolling reaches 80% of your top, okay? Other than that, just change the calculation here: $(obj).offset().top * 0.80 for the amount you want. (=

Browser other questions tagged

You are not signed in. Login or sign up in order to post.