Determining if an item is located within a nested scroll container

How can one detect if a specific element within a scrollable container is currently visible to the user's view (i.e. within the visible area of the scrolling parent)?

Is there a universal method available that does not require iterating through all parent nodes with scroll functionality?

P.S. One possible solution could involve using `getElementAtPoint`, although this approach becomes complex when trying to determine if at least half of the element is visible. Ideally, the solution would incorporate collision detection between the element's rectangle and the viewport.

P.P.S. Another suggestion is to utilize `scrollIntoView` on the targeted element, calculate the positional difference, and then return it to its original position. It seems that `scrollIntoView` consistently manages both the window and inner scrollable elements effectively!

Answer №1

It appears that achieving this task without iteration is quite challenging, especially when considering cross-browser compatibility. However, with some straightforward code, it can be accomplished.

An illustration of how this can be achieved in Internet Explorer is provided below. Unfortunately, other browsers may yield varying results when utilizing

body/html.getBoundingClientRect()
. Furthermore, the treatment of margins differs across browsers (IE disregards them while others take them into consideration).

getVisibilityPercent = function () {
    var target = document.getElementById('target'),
        height = target.offsetHeight,
        parent = target.parentElement,
        targetRect = target.getBoundingClientRect(),
        tLim, bLim,
        percent = 1;
    while (parent) {
        parentRect = parent.getBoundingClientRect();
        tLim = Math.max(targetRect.top, parentRect.top); 
        bLim = Math.min(targetRect.bottom, parentRect.bottom);
        percent *= (bLim - tLim) / height;
        percent = (percent < 0) ? 0 : percent;
        parent = parent.parentElement;
    }
    return +((percent * 100).toFixed(2));
};

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 Ubuntu virtual machine hosted on Google Cloud is experiencing difficulties connecting through Node.js using an external IP address

const express = require('express'); const bodyParser = require('body-parser'); const path = require('path'); const app = express(); app.listen(3000, function(){ console.log('Server is now live on port 3000' ...

What steps can be taken to enable users to draw a path on a Google Map?

I'm working on a new project for a Facebook app that will allow users to map out their marathon route using Google Maps. I plan to utilize mySQL database records to store fixed points along the path (such as specific locations based on latitude and lo ...

A gojs swim lane diagram requires a date axis to provide accurate time representation

I am currently working on a web application that requires a vertical swim lane activity diagram with a customized date axis displayed alongside it. The nodes in the diagram should be positioned based on their date attribute, and users should have the abili ...

Discover how to display the loading time and memory usage of a web page on the footer using the jQuery and AngularJS library

Does anyone know how to display the loading time and memory usage of a web page in the footer using jQuery and AngularJS libraries? I've managed to show the loading time with this jQuery code: <script type="text/javascript"> before = (new Date( ...

Switch the scroll direction in the middle of the page and then switch it back

Yesterday, while browsing online, I stumbled upon this website and was amazed by the unique scroll direction change from vertical to horizontal mid-page. I'm curious about how they managed to achieve that effect. Does anyone have insight into the pro ...

What is the best way to ensure the initial item in an accordion group remains open by default when using NextJS?

I've successfully developed an accordion feature in NextJS from scratch and it's functioning flawlessly. However, I am looking to have the first item of the accordion open automatically when the page loads. Can anyone guide me on how to make this ...

What are some best practices for implementing responsive design using CSS @media queries with makeStyles in React.js Material UI?

const useStyles = makeStyles(theme => ({ wrapper: { width: "300px" }, text: { width: "100%" }, button: { width: "100%", marginTop: theme.spacing(1) }, select: { width: "100%", marginTop: theme.spacing(1) } })); I ...

How to efficiently import Xlsx and csv files using AngularJS

I am looking for a way to extract data in json format from each line of xlsx and csv files using AngularJS. Currently, I am utilizing the angular-file-upload library to access the file as shown below: $scope.LatLongUploader = new FileUploader({ //url ...

Ways to clear an individual form field using element-ui

I'm currently learning VueJS and incorporating the Element-UI framework into my project. One issue I'm facing is that when there's a validation error upon submitting the login form, I'd like to automatically clear the password field. A ...

How can one include a URL as a "URL parameter" when using Express?

In my Node.js application, I've set up a router to listen for requests at api/shorten/: router.get('api/shorten/:longUrl', function(req, res, next) { console.log(req.params.longUrl); } When I enter something like: http://l ...

Associate a variable with a model within a controller

My goal is to bind a variable in my Controller to a model linked to an input like this: <body ng-app="myApp"> <div ng-controller="MyController"> <input type="text" ng-model="myVar1" /> {{ myVar1 }} <br /> ...

What is the process for associating JSON reponses with button actions on a webpage?

I developed a JavaScript script that interacts with a Tableau server API to handle running jobs. The script presents the retrieved jobs on a web page, along with corresponding buttons that enable users to terminate specific jobs. While the script function ...

How can I extract the id of a clicked item and pass it to a different page with Jquery?

Facing an issue where the attribute value of a clicked href tag is not retained after browser redirection. Initially, when clicking on the href tag, the value is displayed correctly. However, upon being redirected to the peoplegallery_album, the id becomes ...

Add numerous submit buttons within a form. Upon clicking on a button, the form should be submitted to a specific URL using AJAX

I have a form with two submit buttons: one labeled as "SUBMIT" and the other as "SCHEDULE NEXT ROUND". When a user clicks on the "SUBMIT" button, the form values should be stored in the database and redirect to the view page. If they click on the "SCHEDULE ...

The error message "TypeError: e.preventDefault is not a function" indicates that

I'm fairly new to JavaScript and jQuery, and I've incorporated two jQuery plugins into my code - jQuery form validator and jQuery form ajaxSubmit. Initially, everything was working fine with normal AJAX submission until I needed to post a file, w ...

Displaying dates on the Amcharts category axis for instances with empty data

I am currently creating a fruit consumption chart for each day, and so far everything is working correctly in the provided example. var chart = AmCharts.makeChart("chartdiv", { "type": "serial", "hideCredits": true, "fixedColumnWidth": '10px& ...

Errors have been observed when using JavaScript variables that begin with the symbol $

For the longest time, I've used JavaScript variable names that begin with $ to signify that they hold jQuery values. For example: $buttons = $( 'button' ); However, a couple of nights ago, I encountered an issue when loading the page in the ...

Sending a post request with data to an ExpressJS server resulted in a 404 error indicating that the server

My setup includes a React frontend communicating with my own ExpressJS API backend running version 4.16.0. Currently, using the fetch method in the React frontend to retrieve data is functioning properly: fetch('/desResData') .then(res = ...

Unable to edit the current value of an input component in ReactJS

I need to implement a search feature for a list of items using ReactJS. You can view the project on JSBIN. The issue I am facing is that when I input 'mi' in the search box to filter by ID, the filtration works correctly but the input value does ...

What causes the difference in behavior between using setInterval() with a named function as an argument versus using an anonymous function?

I can't seem to figure out why using the function name in setInterval is causing issues, while passing an anonymous function works perfectly fine. In the example that's not working (it's logging NaN to the console and before the first call, ...