Tips for automatically scrolling a table inside a div without affecting the overall page scroll on load

In one of my webpage sections, there are dropdowns and images at the top followed by a price grid below the fold. This price grid is contained within a scrollable div element. Initially, upon loading, a price in the grid is already selected but hidden, so the user must scroll down to view it.

My dilemma lies in wanting to automatically scroll the table inside the div to display the active selection without causing the entire page to scroll as well. The goal is for the user not to notice any movement upon page load; rather, they should only see the active choice once scrolling down naturally. Essentially, I aim to have the table scroll to reveal the active row discreetly (below the fold) first, then become visible to the user only when they manually navigate further down the page.

const activeRow = $('#prices_table').find('tr td.active');

activeRow[0].scrollIntoView({block: 'center', behavior: 'smooth' });

The issue with my current code is that it immediately scrolls both the page and the price grid when ideally, I want users to be able to scroll to the grid themselves without interference from automatic scrolling. Various solutions I've come across do involve scrolling the entire page prior to focusing on the div, which isn't suitable for my requirements.

Answer №1

I managed to devise a solution using JQuery.

var hasScrolled = false;

function isInViewport() {
    if (!hasScrolled) {
        var elem = $('#prices_table');
        if (elem !== undefined) {
            var elementTop = elem.offset().top;
            var elemBottom = elementTop + elem.outerHeight();
            var viewportTop = $(window).scrollTop();
            var viewportBottom = viewportTop + $(window).height();

            // return elemBottom > viewportTop && elemTop < viewportBottom;
            if (elemBottom > viewportTop && elementTop < viewportBottom) {
                var activeRow = $('#prices_table').find('tr td.active');
                var containerToScroll = $('#prices_table').find('tbody');
                var tdHeight = activeRow.outerHeight();
                if (activeRow) {
                    if (activeRow[0] !== undefined{
                 $(containerToScroll).scrollTop(($('#prices_table').find('tr td.active').offset().top - $('#prices_table').find('tbody').offset().top) - (tdHeight * 2));
                          hasScrolled = true;
                      }
                 }
            }
        }
    }
}


$(window).scroll(function() {
    isInViewport('#prices_table');
});

Prior to initiating the scroll action, I have implemented a series of checks to ensure its necessity. This prevents unnecessary scrolling and avoids repeated movements.

  • During scrolling, I verify if the element is within view.
  • I further confirm whether the scroll action has already been performed; if not, it proceeds.
  • If the desired element does not exist, the process is halted.
  • Calculations are conducted to determine the required scroll distance; without significant variance, the operation is canceled.
  • The necessary calculations are carried out, and the hasScrolled variable is updated to prevent future repetitions.

Although this method may be more elaborate than anticipated, it effectively achieves the intended outcome.

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

Unable to delete a dynamically inserted <select> element by using the removeChild method

As someone who is new to coding web applications, I am currently working on a project that involves adding and deleting dropdowns dynamically. Unfortunately, I have run into an issue where the delete function does not work when the button is pressed. Her ...

Tips for updating the color of an active navbar:

<div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item mx-4"> <a class="nav-l ...

Error in Typo3 Rendering FieldControl due to insufficient arguments

A plugin has been created for a Typo3 retailer/store database that requires latitude and longitude data for each store. To streamline the process, a button has been added to automatically enter this data through field control in TCA. While this works well ...

Is there a way I can implement lazy loading of results without having to overhaul my entire Laravel + jQuery application built in the Single Page Application style?

I recently created a web application using the Single Page Application concept, but without utilizing any modern technologies or frameworks. In this application, I have a jQuery page that makes dynamic requests to a localhost - a Laravel instance that comp ...

Exploring the latest updates in MUI modern version

The MUI documentation suggests using a modern folder with components designed for modern browsers. Is there a way to configure webpack to automatically rewrite imports like import {Box} from "@mui/material" to use the modern version without manually changi ...

How can JQuery's .load() method be best utilized when working with an image?

I am currently utilizing the .load() function to fetch an image from the server once a button on my webpage is clicked. I then wrap the image in "a href" and "img" tags to convert it into a clickable link, and finally attach it to a div. Here is the code ...

The error occurred in Commands.ts for Cypress, stating that the argument '"login"' cannot be assigned to the parameter of type 'keyof Chainable<any>))`

Attempting to simplify repetitive actions by utilizing commands.ts, such as requesting email and password. However, upon trying to implement this, I encounter an error for the login (Argument of type '"login"' is not assignable to parameter of t ...

When attempting to upload a file from IOS10.3.1, the server received the correct file size but retrieved incorrect data, all of which appeared as

I'm facing issues with correctly uploading files. Our iOS and Android app allow users to select a local image file and upload it to our Nginx server. Issue Summary: Approximately 5% of the total upload requests result in broken image files on the se ...

Javascript does not execute properly in Google Apps Script

Encountering issues while attempting to execute the code provided in Google app script. // 1.foldername = Folder name | 3.templateId = ID of the template to use // 2.SheetId = ID of spreadsheet to use. | 4.rootFolder = ID of the root fold ...

How can I redirect a Spotify API request to save data directly to my local filesystem

I am developing a program for personal use that utilizes Spotify's API. My intention is not to make this software public, but rather to access and analyze my own playlist data. However, I am facing an issue with Spotify's authentication process. ...

Insert an array into a JavaScript code

Looking to convert this PHP array: $array[] = 'bob'; $array[] = 'chris'; $array[] = 'sam'; Into a JavaScript array like this: var array = [bob, chris, sam]; Attempted code just returns var array = [Array];: <script> ...

The jQuery $() constructor and using strings with a forward slash at the beginning

Could you please review this code snippet: http://jsfiddle.net/Bkdgr/1/ The code seems to be malfunctioning. However, implementing one of the two modifications below resolves the issue: Using the pure newItem string in append, rather than enclosing ...

Node.js for Instant Notifications

Currently in the works is a calendar application using Node.js, express.js, and Sequelize. The functionality is straightforward - users can create tasks in the calendar and assign tasks to other system users. One of the challenges I'm facing involve ...

Sending Email Form in PHP using JQuery and Ajax for seamless user experience

Looking to create an email form in HTML with PHP, but running into the issue of the page reloading after submitting? Many people turn to jQuery and AJAX to solve this problem. While you may have come across solutions on Stack Overflow, as a non-native Engl ...

Guide on creating a fluid line in Three.js by connecting two points while clicking the mouse, using buffer geometry

Looking for assistance with drawing dynamic lines on mouse events in a threejs webgl canvas using buffergeometry and raycasting. Any help would be greatly appreciated! ...

Upon a successful AJAX post request, the page fails to display

I'm encountering an issue connecting my front-end JavaScript to my back-end Node/Express. Although the requests from my client-side js to the server return successful, the page I am requesting fails to render. On the server side, here is my code: ap ...

JavaScript Unit Testing seamlessly incorporated with CruiseControl.NET

Currently seeking a framework that offers unit testing for JavaScript. In the future, I will need to connect it to CruiseControl.NET. I have numerous ASP websites that utilize JavaScript, and I am looking to automate the testing process for them. Previousl ...

Setting the value of a custom component property dynamically after the component has been rendered

I'm currently developing an Angular application and have a specific requirement to work on. I am using a custom component with 3 inputs, and I want to bind this custom component tag in the HTML of my page. <my-column [setInfo]="info" [dis ...

Executing JavaScript Function on the Server Side

Recently, I created a JavaScript function that looks like this: function ShowMsg(msg) { $.blockUI({ message: '<div dir=rtl align=center><h1><p>' + msg + '</p></h1></div>', css: { ...

Tips for disregarding modified configuration files in Git

I have a project stored in Git that I plan to install on numerous PCs. Within this project, there is a configuration file called config.ts with the following structure: export var config = { apiUrl: "", local: "", scannerUrl: "", reportPrinter ...