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

Asked

Viewed 673 times

4

When 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 the page down, to div turn up.

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

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

2 answers

7


Check whether $(document).scrollTop() returns 0. If return 0, 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 you scroll the page down, the div turn up.

The event scroll can be used for this. See in 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>
<div id="um-id">Teste</div>
<p class="bla">blablablabla</p>
<p class="bla">dadadada</p>
<p class="bla">qwaqwqaqwqa</p>


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

In this one, you have to use the property elemento.offset().topto give a little 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>
<div id="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>

5

jQuery

Function: $(window).scrollTop()

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

Browser other questions tagged

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