Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if the user scrolled to the top or the bottom of a UL

I need to detect if the user has scrolled to the top or the bottom of the UL in a HTML Page

       <ul id="color-list">
              <li>Red</li>
              <li>Blue</li>
              <li>Purple</li>
              <li>Blue</li>
              <li>Yellow</li>
              <li>Black</li>
              <li>White</li>
       </ul>

I use this code to detect if the user scrolled to the bottom of the page:

window.onscroll = function(evt) {
     if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
         alert("End of Page") ;
     }
 }

Obviously this won't work for the < ul >. What changes should I make guys?

like image 880
Dinuka Jay Avatar asked Oct 17 '15 07:10

Dinuka Jay


2 Answers

$().scrollTop() return how much element has been scrolled from top

$().innerHeight() return inner height of the element(without scroll)

DOMElement.scrollHeight returns height of the content of the element(with scroll)

$('#color-list').on('scroll', function() {
  var scrollTop = $(this).scrollTop();
  if (scrollTop + $(this).innerHeight() >= this.scrollHeight) {
    $('#message').text('end reached');
  } else if (scrollTop <= 0) {
    $('#message').text('Top reached');
  } else {
    $('#message').text('');
  }
});
#message {
  font-weight: bold;
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="color-list" style="height: 150px;overflow-y: scroll">
  <li>Red</li>
  <li>Blue</li>
  <li>Purple</li>
  <li>Blue</li>
  <li>Yellow</li>
  <li>Black</li>
  <li>White</li>
  <li>Red</li>
  <li>Blue</li>
  <li>Purple</li>
  <li>Blue</li>
  <li>Yellow</li>
  <li>Black</li>
  <li>White</li>
  <li>Red</li>
  <li>Blue</li>
  <li>Purple</li>
  <li>Blue</li>
  <li>Yellow</li>
  <li>Black</li>
  <li>White</li>
  <li>Red</li>
  <li>Blue</li>
  <li>Purple</li>
  <li>Blue</li>
  <li>Yellow</li>
  <li>Black</li>
  <li>White</li>
  <li>Red</li>
  <li>Blue</li>
  <li>Purple</li>
  <li>Blue</li>
  <li>Yellow</li>
  <li>Black</li>
  <li>White</li>
  <li>Red</li>
  <li>Blue</li>
  <li>Purple</li>
  <li>Blue</li>
  <li>Yellow</li>
  <li>Black</li>
  <li>White</li>
</ul>
<div id='message'></div>
like image 183
Rayon Avatar answered Sep 21 '22 02:09

Rayon


So you can take the sum of scrollTop() and innerHeight(), and when they are equal to the scrollHeight() the alert is sent:

$('#color-list').on('scroll', function() {
     if($(this).scrollTop() + $(this).innerHeight() >= this.scrollHeight) {
         alert('End of List');
     }
 })
like image 32
Victor Luna Avatar answered Sep 22 '22 02:09

Victor Luna