Joshua Leung
Joshua Leung

Reputation: 2399

How to listen to scroll event on a scrollable element?

enter image description here

I wanna listen to scroll event on a specific element, so that there will be an arrow icon indicating more messages below after the user scrolled up the messages box. Exactly like the Youtube live chat image above.

Or is there an another way doing this?

Upvotes: 13

Views: 26346

Answers (2)

jo_va
jo_va

Reputation: 13963

You can use the scroll event triggered by the div and attach an event listener with addEventListener().

Here is an example that dynamically adds more items to a list when the user scrolls to the bottom.

To detect when the user reaches the bottom, use scrollHeight - scrollTop === clientHeight.

If you want to scroll to the bottom, just set scrollTop = scrollHeight.

const list = [];
const ul = document.querySelector('ul');
const len = document.querySelector('span');
const button = document.querySelector('button');

button.addEventListener('click', () => {
  ul.scrollTop = ul.scrollHeight;
});

const appendBlock = () => {
  if (list.length >= 200) return;
  list.push(...Array.from({ length: 20 }, (_, i) => i + list.length));
  ul.innerHTML = list.map(i => `<li>Elem ${i}</li>`).join('');
  len.textContent = list.length;
}

ul.addEventListener('scroll', event => {
  const e = event.target;
  if (e.scrollHeight - e.scrollTop === e.clientHeight) {
    appendBlock();
  }
});

appendBlock();
#container {
  position: relative;
  border: 1px solid black;
  border-radius: 5px;
}
ul {
  height: 110px;
  overflow: auto;
}

button {
  position: absolute;
  left: 50%;
  bottom: 10px;
  width: 30px;
  height: 30px;
  border-radius: 30px;
  background: #08f;
  color: white;
  font-weight: bold;
  font-size: 17px;
  cursor: pointer;
}
<div id="container">
  <ul></ul>
  <button>↓</button>
</div>
<br>
Number of items: <span id="len"></span>

Upvotes: 2

Darryl Huffman
Darryl Huffman

Reputation: 2589

You can listen for a scroll event on any element using the following code:

element.addEventListener("scroll", function(){
    // do stuff
});

You can then get the current scroll position of that element by using element.scrollTop

From here, you can check to see if the element's scroll position is less than its total height. If it is, display your button to scroll back down. On click of the button with the down arrow, you simply use element.scrollTo() which even has built in easing effects in modern browsers. Just pass the scroll value as the height of the containing element.

Upvotes: 12

Related Questions