How to identify if the user is at the top of the page?

4

Upon entering the site the page will be displayed from the top (by default) , how to do to identify if the page is at the top using JavaScript pure and > jQuery ?

Examples:

  • If the page is at the top, hide the <div id="um-id"> , but if scroll down the page, div appears.

  • If the page loads and rolls directly to an element with id , such as exemplo.com/#rodape and then the user scrolls to the top, an alert appears.

These are just usage examples, the question is how to identify if you are at the top of the page using JavaScript and / or jQuery ?

    
asked by anonymous 18.08.2018 / 00:58

2 answers

7

Verify that $(document).scrollTop() returns 0. If you return 0, it is because it is at the top of the page. If you do not want to use jQuery, use document.documentElement.scrollTop .

  

If the page is at the top, hide the <div id="um-id"> , but if the page scrolls down, div appears.

The scroll event can be used for this. See the code below:

$(document).scroll(function() {
    $("#um-id").toggle($(document).scrollTop() !== 0);
});
.bla {
    height: 200px;
}

#um-id {
    background-color: red;
    position: fixed;
    display: none;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script><divid="um-id">Teste</div>
<p class="bla">blablablabla</p>
<p class="bla">dadadada</p>
<p class="bla">qwaqwqaqwqa</p>
  

If the page loads and rolls directly to an element with id , such as exemplo.com/#rodape , and then the user scrolls to the top, an alert appears.

In this one, you have to use the elemento.offset().top property to help. See the code below:

var rodape = $("#rodape");
$(document).scrollTop(rodape.offset().top);
$(document).scroll(function() {
    $("#alerta").toggle($(document).scrollTop() < rodape.offset().top);
});
.bla {
    height: 200px;
}

#alerta {
    background-color: red;
    position: fixed;
    display: none;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script><divid="alerta">Teste</div>
<p class="bla">blablablabla</p>
<p class="bla">dadadada</p>
<p class="bla" id="rodape">AQUI!</p>
<p class="bla">qwaqwqaqwqa</p>
    
18.08.2018 / 01:02
5

jQuery

Function: $(window).scrollTop()

$(document).scroll(function() { 
   if($(window).scrollTop() === 0) {
     // Coloque aqui o que você deseja fazer se estiver no topo
   }
});
    
18.08.2018 / 01:04