Ways to detect the scroll event on a scrollable container?

https://i.sstatic.net/Vx3M7.jpg

I am looking to implement a scroll event listener on a specific element, where an arrow icon will appear when the user scrolls up in the message box. Similar to the functionality seen in the Youtube live chat image above.

Are there any alternative methods for achieving this?

Answer №1

If you want to detect a scroll event on any element, you can use the code snippet below:

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

To retrieve the current scroll position of the element, simply access element.scrollTop

You can then check if the element's scroll position is less than its total height. If it is, show a button for scrolling back down. When the button with the downward arrow is clicked, you can easily utilize element.scrollTo(), which includes smooth scrolling effects in modern browsers. Just provide the scroll value as the height of the containing element.

Answer №2

You can utilize the scroll event activated by the div container and add an event listener using addEventListener().

For instance, you can create a functionality that dynamically appends more items to a list as the user scrolls to the bottom.

To determine when the user has reached the bottom, check if

scrollHeight - scrollTop === clientHeight
.

If you wish to automatically scroll to the bottom, 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The magnitude of each new keystroke is squared compared to its predecessor

exploring the relationship between keyboard and console inputs Each subsequent e.key entry is occurring twice as frequently as the previous one. Once it reaches 8-9 characters, the rendering frequency skyrockets to over 1000 times per character. Here&apos ...

Converting a Ruby array into a KnockoutJS object

I'm having an issue with converting a Ruby array to JSON, saving it to MySQL, and then loading it into KnockoutJS. The problem is that the array remains a JSON string and I can't iterate over it. tags = `/usr/bin/svn ls #{svn_repo_url}`.split("/ ...

Retrieving text data from the JSON response received from the Aeris API

I am attempting to showcase the word "General" text on the HTML page using data from the API found under details.risk.type. The JSON Response Is As Follows... { "success": true, "error": null, "response": [ ...

What is the process for updating the combination selector for each product within a specific category in PrestaShop 1.7?

We have a range of products in a specific category, each offering multiple pack sizes with varying prices (e.g. 1, 3, 5, 10, 25, 50, 100). EDIT: The homepage features these products displayed using an owl-carousel within a div element: https://i.sstatic.n ...

Encountered an issue retrieving audio during recording with Recorder.js

I've come across a scenario where I'm utilizing the Recorder.js Demo for recording audio. Interestingly, it works perfectly on Linux but encounters an issue when used on Windows. A pop-up alert stating "Error getting audio" shows up. Here's ...

I'm experiencing a lack of feedback while implementing jQuery/AJAX with JSONP

Attempting to perform a cross-domain request using jQuery/AJAX, I have the code below; $.ajax({ url: "http://www.cjihrig.com/development/jsonp/jsonp.php?callback=jsonpCallback&message=Hello", crossDomain:true }) .done(function( msg ) { alert( ...

You can either use handleSubmit() as an onSubmit function or simply pass onSubmit as a prop

I attempted to integrate the redux form into my stepper component. Following a tutorial, I implemented async form from In the tutorial's demo, everything was working smoothly. However, upon clicking the sign-up button, I encountered an ...

Catching the Selenium NoSuchElementError in JavaScript is impossible

Update: It's puzzling why this was marked as answered since the linked questions don't address the issue at hand and do not involve Javascript. My objective is to detect this error, rather than prevent it, given that methods like invisibilityOfEl ...

The Vue component fails to refresh after modifications to the state in the Pinia store

I'm currently immersed in my inaugural vue application, focusing on constructing the login functionalities. To handle State management, I've implemented pinia. I've set up a Pinia Store to globally manage the "isLoggedIn" state. import { def ...

Excluding null values when using Mongoose populate query: A simple guide

I'm currently working on an app where I've defined 2 models. const UserSchema = new Schema({ _id: Schema.Types.ObjectId, account:{ type: String, unique: true }, email: String, first_name: String, last_name ...

Creating a Duplicate of the Higher Lower Challenge Game

To enhance my comprehension of React, I am constructing a replica of the website: Instead of utilizing Google searches, I opted for a dataset containing Premier League stadiums and their capacities. Up to this point, I have crafted the subsequent script: ...

I am creating an HTML page that incorporates p5.js, and the text I'm rendering

It seems like the draw loop is continuously refreshing every x seconds, causing this behavior. Is there a way to slow down or disable the frame update without affecting the video refresh rate? I was thinking of adding an fps counter and implementing an i ...

What are the key principles of designing web and native mobile applications using React.js architecture?

I am intrigued by the idea of incorporating React.js for server-side rendering into my web service. However, I am facing a challenge when trying to transition from my current web service built with Express.js. At present, my web service caters to two platf ...

Why isn't my ajax call working after using window.close?

Whenever I click the button on my page, a small window opens and the value from the window is sent to my controller before closing. However, I noticed that when I include the window.close() line, the controller does not get hit. It works perfectly fine wit ...

The synergy of THREEJS and GC in creating dynamic and interactive

In an effort to optimize my threejs scene, I noticed that the CPU usage was high even when the scene was not in use. After exploring various solutions, I tried removing the memory of mesh using the dispose() method to prevent memory leaks. labelMesh[i].ge ...

Implementing clickable table rows in React Router Link for seamless navigation

I'm relatively new to working with React. In my project, there is a Component called Content, which acts as a container for two other components - List and Profile. class Content extends Component{ <HashRouter> <Route exact path="/ ...

Manipulate component properties using CSS hover in React with Material-UI

I am attempting to modify the noWrap property of a Typography element when hovering over it. I have defined a custom CSS class for the parent element and the hover functionality is working correctly. However, I am unsure how to adjust the noWrap property u ...

Transforming a Standard Query into a JSON Clause Hierarchy

I am looking to create a query system for my application that can be utilized by external systems for configuring based on specific conditions. My plan is to utilize a JSON Clause tree on the backend, which will be evaluated recursively. [ "AND&quo ...

Stop the click event from firing on child elements of a parent element that is currently being dragged

Below is the structure of a UL tag in my code: <ul ondrop="drop(event)" ondragover="allowDrop(event)"> <li class="item" draggable="true" ondragstart="dragStart(event)" ondrag="dragging(event)"> <div class="product-infos"> ...

Sending an array of strings from an ajax call to an MVC controller

I'm encountering an issue where I have an array that I build up when a row is selected in my bootstrap data table. The problem arises when I try to pass this array from my view to the controller, which is supposed to fire up a partial view. Strangely, ...