Scrolling a div automatically without affecting its parent element

On a page, I have a scrollable list of items that can be updated with a PUT request. Once the update is successful, another network request is made to fetch the updated list. The goal is to automatically highlight the recently updated item in the list.

Although the code successfully accomplishes this task, there is an issue where not only does the list scroll but the entire page also moves somewhat.

The structure of my list is as follows:

<div className={cx(styles.body)}>
  <div className={styles.squadList}>
    {squadList.map((squad, index) => {
       const isSelected =
         squad.squadId === squadSelected.squadId
         ? "selected"
         : null;
       return (
          <div
            className={cx(styles.item, {
             [styles["item--selected"]]: isSelected,
            })}
            key={index}
           id={`squad-list-item-${squad.squadId}`}
          >
           <div className={styles.details}>
               <span className={styles.title}>
                   {squad.squadName}
               </span>
               <span className={styles.members}>
                    {squad.memberCount} members &nbsp;
                    {renderAdminIcon(squad, isSelected)}
               </span>
           </div>
         </div>
       );
    })}
  </div>
</div>

After the successful put request and refetch, the following code is executed:

const tgtElement = document.getElementById(
    `squad-list-item-${squadSelected.squadId}`
);
tgtElement.scrollIntoView();

This script successfully scrolls the desired item to the top of the list, but it unfortunately causes the entire page to scroll slightly as well.

Answer №1

To achieve this, you need to scroll the div to reach the desired element.

Start by obtaining the element's offsetTop, then adjust the div's top scroll position to match the element's offset from the top.

const divToScroll = document.getElementById("divToScrollId");
const tgtElement = document.getElementById(
    `squad-list-item-${squadSelected.squadId}`
);

// This is where the magic happens
divToScroll.scrollTop = tgtElement.offsetTop;

This method will work as long as the div being scrolled has a CSS position set to relative.

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

Proceed with another ajax request only when the previous one has been successfully completed and loaded

While scrolling down and loading content into my page, I am facing an issue. The ajax executions load too quickly, causing the subsequent calls to not receive correct information from the first ajax call that is loaded into the DOM. How can I ensure that ...

Certain components in Next.js are not properly reflecting the styles defined in Tailwind CSS

After successfully building a single-page portfolio site on Next using Tailwind, I decided to expand by adding a second page to my project. I created a new file in the pages directory and referenced a new component. While the content is accessible via the ...

Using C# ASP.NET to create an array that corresponds to a JavaScript array

I am trying to figure out how to assign an array in my C# code behind and call a JavaScript function that uses that array. The JavaScript function looks like this: <script type="text/javascript"> var TotalData = new Array(); function S ...

Combining meshes results in a lower frame rate

I have combined approximately 2500 meshes, each with its own color set, but my FPS is lower than if I had not merged them. Based on THIS article, merging is recommended to improve FPS performance. Is there something I am overlooking? var materials = new ...

Use Python to enter a value on a webpage coded in HTML

My current project involves automating the input of values into a webpage. However, I have encountered a significant hurdle with the Mechanize library as it does not recognize the forms on my page which are <input> elements, unlike the typical form.n ...

I wasn't able to use the arrow keys to focus on the select box in my table, but I had no problem focusing on all

I'm a novice in jQuery and I encountered a situation where I have select boxes and text fields within my table. I successfully implemented arrow key functionality (down for next, up for prev) for shifting focus to the field by assigning classes to eac ...

The dialogue box fails to appear when accessed from the dropdown menu shadcn

I'm encountering an issue while using nextJS with shadcn. I am attempting to open a dialog from a dropdown menu, but instead of opening, it just closes the dropdown menu. My assumption is that I either need to utilize ref and states or position the al ...

Transforming retrieved data into an array using Node.js

Got some data from a URL that looks like this: data=%5B1%2C2%2C3%2C4%2C0%5D which when decoded is [1,2,3,4,0]. Used the snippet below to parse the data: var queryObj = querystring.parse( theUrl.query ); Seems like it's not an array. How can I con ...

Guide to extracting information from a Node.js http get call

I am currently working on a function to handle http get requests, but I keep running into issues where my data seems to disappear. Since I am relatively new to Node.js, I would greatly appreciate any assistance. function fetchData(){ var http = requir ...

Suggestions for a JavaScript tool that automatically crops images

Is there a tool available, either browser-based or in Java, that can analyze an uploaded image, identify different characters within it, and crop them out into separate images? For instance, if this image contains three unique runic symbols, I would like ...

The $postLink() method in the controller is encountering a null value for this.$scope

class pageController { constructor($scope, MyEditableGrid) { this.$scope = $scope; this.MyEditableGrid = MyEditableGrid; this.myEditableGrid = { appScope: this.$scope, ..... } } $postLink ...

What is the best way to format and return a result object list in JavaScript or Angular?

I have a question regarding the use of for loops in JavaScript or utilizing Angular to output the resulting object list. Here is an example of an object list: var alist = []; alist = [ { 'code': 1000, 'type': 'C' ...

Ensure that the innerHTML of the span tag does not contain line breaks

Is there a way to prevent the span tag inside the div with the item class innerHTML from causing a line break, regardless of its length? I also need to ensure that any innerHTML exceeding the item width does not overlap but is hidden. I have attempted usin ...

Create a ReactJS page with no pre-generated additional pages

Just ventured into the world of reactjs and created my first app. Now I'm trying to build a production version using the command: npm run build However, all I get is a blank index.html file generated. Why is this happening? I have multiple routes in ...

Tips for showing data from Ajax responses on an HTML page

In my code, there are two JavaScript functions: The function fetch_items is responsible for returning data in the form of stringvalue. On the other hand, the function extract_items($arr) passes values to the fetch_items function. function fetch_items ...

Unable to create slides with Fancybox if the content is in HTML format

I'm not sure if this issue is a bug or if it's just a restriction of fancybox. Can anyone confirm if it's possible to create a gallery using HTML elements? I've been attempting to accomplish this for hours without success. Here is the ...

Enhancing User Experience with Animated jQuery Progress Bar

I came across a cool tutorial on animating progress bars: The only issue was that the progress bar didn't utilize jquery, and there wasn't information on linking multiple buttons to it. After some searching, I found another tutorial that address ...

Implement the TypeScript handleChange function for input fields and dropdown menus

Currently, I am in the process of developing a form using TypeScript and Material-UI components. My objective is to create a change handler function that can be utilized for both select and textfield changes. Below are my state and functions: const [re ...

Integrate JavaScript date into the gulp-rev workflow

I have been encountering an issue while using the gulp-rev plugin to add a revision of my app/html page generated by the Yeomann webapp generator. My workflow involves zipping the app and then adding a revision, but I am having trouble replacing the hash t ...

Troubleshooting Problems with jQuery's .remove() Function

I attempted to create a simple game using JS and jQuery, keeping in mind that I am new to both languages. My goal was to create a function that allows users to delete their save within the game. However, despite my efforts, I faced issues with the function ...