Navigate to a different position of a specified element within an expanding pivot grid

I'm currently dealing with a pivot table/grid that allows users to expand and collapse rows. My challenge is figuring out how to scroll to an expanded row after an expansion occurs. Typically, I use the following code for scrolling functions:

            Actions actions = new Actions(Browser);
        actions.MoveToElement(plusMinusIcon).Perform();

and this:

            var coordinates = plusMinusIcon.Location;
        ((IJavaScriptExecutor)Browser).ExecuteScript("window.scrollTo(0," + coordinates.Y + ")");

These scrolling methods work fine before any expansion, when the page isn't too large and the scrollbar isn't too long. However, if I expand a row, causing more rows to appear and the page to become much larger, the scroll method fails to reach the correct location and instead scrolls elsewhere (even though it worked fine for the initial expansion). During debugging, I observed that the scroll does move the page slightly, but not to the intended element. What could be causing this issue? Do I need to calculate new coordinates for scrolling?

Below is the line of code from my test:

            Page.ClickExpansionIcon(VRptPage.VRptProjWOutActualsPvtGridBodyArea, "All Hours", 2);

Here is the method used to scroll into view and click the element:

        /// <summary>
    /// Expands the first instance in the grid of either All Days or All Hours header cell
    /// <param name="pvtGridBodyAreaElement">The element that contains the body elements of any pivot grid. i.e. "Page.VRptErrorMeasuresPvtGridBodyArea"</param>
    /// <param name="rowNumber">The exact row where the desired cell exists</param>
    /// <param name="timeFormatToExpand">Either 'All Days' or 'All Hours', 'All Dates', or 'All 1/4 Hours'</param>
    /// </summary>
    public void ClickExpansionIcon(IWebElement pvtGridBodyAreaElement, string timeFormatToExpand, int rowNumber)
    {
        var cssSelectorString = string.Format("th[title='{0}']", timeFormatToExpand);

        // Find the element that can be expanded
        var expansionCapableElem = pvtGridBodyAreaElement.FindElements(By.CssSelector(cssSelectorString))[rowNumber - 1];

        // Find the + or - icons within the parent cell. 
        var plusMinusIcon = expansionCapableElem.FindElement(By.CssSelector("span[data-expand]"));

        var coordinates = plusMinusIcon.Location;
        ((IJavaScriptExecutor)Browser).ExecuteScript("window.scrollTo(0," + coordinates.Y + ")");

        Thread.Sleep(2000);
        plusMinusIcon.Click();
        Thread.Sleep(2000);
    }

Answer №1

Although this example is written in C#, the concept can easily be grasped.

  var jsExecutor = (IJavaScriptExecutor)driver;
  var targetElement = // locate a specific element;
  string highlightScript = @"$(arguments[0]).css({ ""border-width"" : ""2px"", ""border-style"" : ""solid"", ""border-color"" : ""red"" });";
    jsExecutor.ExecuteScript(highlightScript, new object[] { targetElement });

Answer №2

After a thorough investigation, I managed to identify the root cause of the issue. Interestingly, it turned out that the problem had nothing to do with the dynamics of the pivot table as originally suspected. It was actually related to how the scroll bar behaved when the page size allowed it to reach the element but still had additional space to scroll further down. In order to address this glitch, I implemented a solution where the page would scroll just above the target element:

// Scroll to the position slightly above the plusMinusIcon
var coordinateAboveIcon = plusMinusIcon.Location.Y - 100;
((IJavaScriptExecutor)Browser).ExecuteScript("window.scrollTo(0," + coordinateAboveIcon + ")");

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

Incorporating payment processing into React Native using JavaScript

I am looking to incorporate payment processing into my react native app, but I encountered an issue with using RN's webview as it does not render on the web platform. Additionally, I need to be able to read the response from the server. Can someone re ...

Guide on setting a JSON object using the getJSON method

In my coding project, I am trying to assign values of lat and lng from a JSON object named branch to a variable called jsonData. When I use console.log to check jsonData.responseJSON.positions.length or jsonData.responseJSON.positions[0].lat, etc. I c ...

Instructions for making dropdown menus that dynamically reduce their options as you make selections:

I have an HTML form structured like this: Within the dropdowns, there is a uniform list of choices: Option 1, Option 2, Option 3. Users must select a value for each key, which currently functions correctly: Yet, I am seeking to enhance this functionality ...

Background PHP/JS authentication through HTTP

Recently, I developed a PHP website that includes embedded web-cam snapshots which refresh every 2 seconds using JavaScript. For the first camera, I can easily log in using URL parameters like this: cam1-url?usr=usr&pwd=pwd. However, the second camer ...

How can I use AJAX to automatically populate a dropdown menu with cities in a PHP MVC application?

Within a PHP MVC setup, there is a file named city.php in the model section which defines a city class. The city class contains a method called getCitiesByProvince('ProvinceId') that retrieves all cities for a given province. When a user picks ...

What are the steps involved in incorporating a REST API on the client side?

Hey there! Today I'm working with a simple Node.js express code that functions as a REST API. It works perfectly when I use Postman to send requests with the GET method, as shown in the code below. However, when I try to implement it on the client sid ...

There was an error in the syntax: an expression was expected, but instead the character '}' was found in mongoDB

Encountering the error message SyntaxError: expected expression, got '}' @(shell):1:0 when executing a query in the shell. db.address.aggregate([ { "$project": { "applications": { "$filter": { ...

Identifying the floor or ground using a webcam in motion: A step-by-step guide

I am currently facing a unique challenge: In my project, I have markers (specifically Hiro, A, Kanji) displayed on banners, and I need to show a 3D model (such as augmented reality) when the marker is recognized. Everything works well so far, but here&apo ...

Is it possible to simultaneously use the same plugin with various configurations and unique names in Vue?

I'm attempting to utilize the Vue Currency Input plugin, specifically with two different configurations simultaneously: import Vue from 'vue' import VueCurrencyInput from 'vue-currency-input' const options = { globalOptions: { ...

Tips on customizing the appearance of React rendering components

<div> <h3>{this.props.product.name}</h3> <h3>{this.props.product.code}</h3> {this.renderColors()} <article> <div da ...

Approach for cycling through a table

My website has a dynamic table that requires checking if certain criteria are met using Selenium. The number of rows in the table varies, with 3 rows on some days and 5 rows on others. I am looking to create a method that will compare values to ensure tha ...

Activate background functionality while modal is active in Bootstrap 4

I have come across similar questions addressing the need to change the following: .modal-backdrop { display: none; } However, my modal does not have this .modal-backdrop. I am unsure if this is a new feature in Bootstrap 4, but the mentioned solution ...

Is there a way to utilize javascript std input/output in repl.it effectively?

I created a straightforward program that calculates the factorial of a specified number, and I am interested in running it on repl.it. During its execution, I would like to interact with standard input and output through the command line. Is there a way ...

Categorize elements in an array based on a specific keyword

Struggling with my AngularJS (1) application, I can't seem to figure out how to split an array of items into separate arrays grouped by item. In simpler terms, I have an array with different items and I want to group them by their uuid like this: [ ...

Obtain the quiz test score in plain text format without any pop-up messages

I'm looking to add an online quiz feature to my blog. Currently, the code I have displays the result score in a popup when the user clicks on "View Results." However, I would like to show the result as text within the form itself, similar to the imag ...

The split function of a string displays an undefined result

My goal is to extract all characters that come after the equal sign within a URL: let url = this.$route.query.item console.log(typeof(url)) // outputs string let status = url => url.split('=')[1] When I run the code, it shows &apo ...

Is there a way to integrate PHP functionality into JavaScript?

When it comes to using JavaScript and PHP together, a common challenge is retrieving information from a database and utilizing that data in a JavaScript function. In my case, I need this functionality for implementing password change functionality on a w ...

Ways to perform a redirect following data retrieval from a post request

I am working on a post method for a servlet, where the servlet returns a web page after forwarding a request to another page. Instead of directly redirecting using window.location = "/AnotherServlet", I have tried various solutions including passing parame ...

Enhancing PHP function speed through pre-compilation with Ajax

I am curious about compiling server side functions in PHP with Ajax, specifically when multiple asynchronous calls are made to the same server side script. Let's consider a PHP script called "msg.php": <?php function msg(){ $list1 = "hello world ...

Swapping mouse cursor using JavaScript

Currently, I am working on a painting application in JavaScript that utilizes the Canvas Object. I would like to customize the mouse cursor when it hovers over the Canvas object. Can anyone advise me on how to accomplish this? ...