Alert when scroll reaches top of page

Asked

Viewed 71 times

0

In the code below, the alert is triggered when the scroll arrives at the end.

$('#messages').scroll(function() {
    if ($(this).scrollTop() + $(this).height() == $(this).get(0).scrollHeight) {
        alert('a rolagem chegou ao fim, fazer algo aqui.');
    }
});

However, when loading the page, the scroll starts at the bottom.

How can I do the reverse of the above code, and alert when the scroll reaches the top?

2 answers

4


Just put a else if checking whether the scrolling has reached 0:

I put a Math.ceil() in the example only to work correctly on the snippet.

$('#messages').scroll(function() {
    if (Math.ceil($(this).scrollTop() + $(this).height()) == $(this).get(0).scrollHeight) {
        console.log('a rolagem chegou ao fim, fazer algo aqui.');
    }else if($(this).scrollTop() == 0){
        console.log('a rolagem chegou ao início, fazer algo aqui.');
    }
});
html, body{
   overflow: hidden;
   height: 100vh;
}

#messages{
   height: 50%;
   overflow: auto;
   background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="messages">
   mensagens início
   <br><br><br><br><br><br><br><br><br><br><br><br>
   mensagens fim<br>
</div>

1

Try it like this:

$('#messages').scroll(function() {
    if ($(this).scrollTop() == 0) {
        alert('a rolagem chegou ao inicio, fazer algo aqui.');
    }
});

Browser other questions tagged

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