Verify the position of the scrollbar without triggering any reflow

Here is a function I have:

        is_bottom: function() {
            if (settings.scrollBottomOffset === -1) {
                return false;
            } else {
                var scroll_height, scroll_top, height;
                scroll_height = self[0].scrollHeight;
                scroll_top = self.scrollTop();
                height = self[0].offsetHeight;
                var limit = scroll_height - settings.scrollBottomOffset;
                return scroll_top + height > limit;
            }
        }

I use this function to determine if my content is at the bottom before rendering the html. If it is, I move the scrollbar on the element to the bottom after adding new content.

The issue is that this causes reflow which I want to avoid, as it results in double layout - once when checking if it's at the bottom and again after rendering the new content.

I believe optimizing this part of the code could make a difference, especially during heavy rendering operations. Even saving milliseconds can matter.

So, my question is, is there an alternative way to check if the scrollbar is at the bottom? Perhaps using a sentinel element and CSS positioning until it's hidden (e.g., with visibility: hidden). It might involve utilizing new intersection or resize observers for better performance, possibly improving only in certain browsers.

EDIT: I've realized that I can first check if my content has a scrollbar. The code that triggers multiple re-renders doesn't even display a scrollbar:

    function have_scrollbar() {
        return fill.outerWidth() !== self.outerWidth();
    }

The problem here is that this also leads to reflow. Is there a way to check if an element has a scrollbar without causing reflow?

Answer №1

It appears that you are asking about listening to a scroll event on the body element. You can achieve this by attaching an event handler to the body element, and within that, extract information about the current scroll state from the event object.

Answer №2

I have successfully tackled almost all of my tasks by implementing the intersection observer method and placing a dummy element at the bottom of my scrollable container. As stated in MDN, this API functions when the parent has a scrollbar, allowing me to detect if an element is at the bottom:

function checkIfBottomIsReached(intersections) {
    console.log(intersections[0]);
    isBottomDetected = intersections[0].intersectionRatio === 1;
}
function setupBottomDetection() {
    if (window.IntersectionObserver) {
        var scrollMarker = $('<div class="scroll-marker"/>').appendTo(self);
        bottomObserver = new IntersectionObserver(checkIfBottomIsReached, {
            root: self[0],
            rootMargin: '0px',
            threshold: 1.0
        });
        bottomObserver.observe(scrollMarker[0]);
    }
}

It appears that this method works accurately for detecting when the user scrolls to the very bottom with a marker that only requires height: 1px;. Additionally, to avoid extra spacing, you can implement margin-top: -1px.

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

How to capture and log request and response data when using the HttpService in NestJS?

Is there a way to log requests, responses, and errors using the HttpService within the HttpModule? In the past, I have used Interceptors with AXIOS. While HttpService wraps axios, I'm having trouble adding interceptors. There doesn't seem to be ...

Ways to retrieve an array saved in another JavaScript document

I am in the process of developing my own lorem ipsum application and keen on maintaining clean code by storing my word bank in separate files. How can I retrieve an array stored in a different JavaScript file? Rather than manually inputting harry = ["", "" ...

Make the HTML element expand to the remaining height of the viewport

Need help with creating a section that automatically fills the remaining viewport height below the navigation bar. The section includes a centered div and background image, along with a button at the bottom for scrolling down by one full viewport height. H ...

Code for Rotating the Wheel - MINUS javascript

Exploring the possibility of creating a spin the wheel effect like this using only HTML and CSS, no Javascript involved Seeking references or examples to determine feasibility. ...

Guide on transforming an array of objects into a fresh array

I currently have this array: const initialData = [ { day: 1, values: [ { name: 'Roger', score: 90, }, { name: 'Kevin', score: 88, }, { name: 'Steve&apo ...

How to automatically insert a page break after a certain string in an array using JavaScript

I've created a code that is intended to implement page breaks after a specific number of new lines or words. I have defined an array that indicates where these breaks should occur within my element. In the example provided in my jsFiddle, you can see ...

Displaying fresh data from a JSON URL by clicking on a button and dynamically refreshing the view in

Apologies if this question has been asked before, but I couldn't locate it. I’m currently engaged in an Angular project where I’ve loaded an external JSON file using http. The data is presented through ngRepeat. When a button is clicked, I aim t ...

Generate the Xpath for the mentioned href element to use with Selenium Webdriver

I need help creating the Xpath for a specific href element using Selenium webdriver with only IE browser. The HTML code I am working with is as follows: I am looking to find the Xpath for: . Can someone assist in generating the correct Xpath expression ...

An AngularJS-powered dynamic navbar

Apologies if my explanation is unclear, but I am struggling to find a simple way to convey the following information. I have set up a navigation bar that displays different categories of articles. These navigation items are pulled from a database and can ...

Determining when a message has been ignored using php

One of the features I am working on for my app is adding announcements, which are essentially personalized messages to users. Once a user receives a message and dismisses it, I want to ensure that specific message does not appear again. Here is the PHP co ...

What could be the reason for my Express server returning a 404 error for all files other than index.html?

Currently, I am delving into Node.js with Express in order to set up a small server for educational purposes. Strangely, every request made to files linked within my index.html file, such as the .css, .js, and image files, results in a response code 404. ...

Sending data to a React component from regular HTML

I have a question about implementing a method to pass custom attributes from HTML elements as props to React components. Here's an example: function someFunction(props) { return <h1>props.something</h1> } HTML: <div id="someEl ...

The quirks of JSON.stringify's behavior

I am in the process of gathering values to send back to an ASP.NET MVC controller action. Despite using JSON.stringify, I keep encountering Invalid JSON primitive exceptions and I am unsure why. I have a search value container named searchValues. When I i ...

Adding JQuery elements to the map pane

I recently decided to upgrade one of my projects to use the Google Maps API v3 instead of v2. In v2, I used the following code to append a div to the map pane: $("#marker_popup").appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE)); Is there a straightforward ...

Animating a mesh in three.js with color transitioning using tween.js

I've been struggling to accomplish this task. My goal is to change the color of a ConvexGeometry mesh when hovered over. So far, I can successfully change the mesh's color without any issues. The problem arises when I attempt to create a smooth ...

Optimizing Angular's ng-repeat for efficient updates by restricting the watch functionality to the relevant iteration

My task involves creating a table where users can edit certain fields in each row, which will impact other fields within the same row. Due to this requirement, I cannot use bind-once for all the rendered data. To address this issue, I attempted using the ...

Lack of communication between Node.js modules

Currently, I am diving into the world of node.js as part of a personal project to enhance my skills. To maintain best practices, I have been segmenting my code into different modules. However, I have hit a roadblock where a module I created is not communic ...

What steps can be taken to implement CSS rules on an HTML element with ExtJS?

In my ExtJS 4 project, I am working on drawing an image inside a panel and slider field. My goal is to adjust the opacity of the image based on the value of the slider field. I understand that I can use CSS rules like opacity and filter:alpha(opacity=); t ...

Unable to establish React API communication on cloud-based IDE for MERN Stack development

Exploring the MERN stack through this informative tutorial: https://medium.com/@beaucarnes/learn-the-mern-stack-by-building-an-exercise-tracker-mern-tutorial-59c13c1237a1 I've opted to use goorm IDE, a cloud platform similar to cloud 9 IDE. As I pro ...

Retrieving information from a MYSQL database table and populating a text field with AJAX and PHP

Is there a way to use AJAX to display the data from an array that is called in getword.php into a text field in index.php? Let's take a look at the code below: Here is the code snippet from index.php: <body> <div class="container" ...