JavaScript scrolling allows for scrolling to a point where the element is no longer visible on the screen

I've been diving into the world of selenium and Java, attempting to utilize JavaScript for scrolling down to a specific element. However, I've encountered an issue where my script scrolls past the element, rendering it out of view. The error message displayed in the console reads:

Exception in thread "main" org.openqa.selenium.ScriptTimeoutException: script timeout

I'm puzzled as to why this is happening. Can anyone shed some light on what might be causing this problem?

public class JavaScriptScrolling {

    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        
        driver.get("https://www.asda.com/");
        
        Thread.sleep(5000);
        
        driver.findElement(By.xpath("//button[@id='onetrust-accept-btn-handler']")).click();
        
        Thread.sleep(3000);
        
        JavaScriptUtils jUtil = new JavaScriptUtils(driver);
        
        WebElement element = driver.findElement(By.xpath("//a[text()='Explore more']"));
        
        jUtil.scrollIntoView(element);
        
        element.click();
    }

}

The scrollIntoView method from the JavaScriptUtils class used for scrolling is as follows:

public void scrollIntoView(WebElement element) {
        js.executeAsyncScript("arguments[0].scrollIntoView(true);", element);
    }

Answer №1

The issue you are experiencing could be related to the scrollIntoView function. One way to address this problem is by modifying the scrollIntoView method to ensure that the element aligns properly with either the top or bottom of its container. To achieve this, follow these steps:

public void adjustScrollPosition(WebElement element, boolean alignToTop) {
    String script = "arguments[0].scrollIntoView(" + alignToTop + ");";
    ((JavascriptExecutor) driver).executeScript(script, element);
}

Subsequently, you can utilize this method by specifying the alignToTop parameter as either true or false depending on your specific requirements. Set it to true if you want the element aligned to the top, and false if alignment to the bottom is desired.

// scroll element to align with the top
adjustScrollPosition(element, true);

// scroll element to align with the bottom
adjustScrollPosition(element, false);

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 do I start using Google Analytics: application.js, ga.js, or a beginner’s guide?

Hello there! I was wondering if anyone could provide a comprehensive guide or step-by-step tutorial on setting up Google Analytics with some examples. The information I found so far only covers signing up and obtaining a tracking code, but it doesn't ...

Determine if an object has been submitted in a MEAN / AngularJS application

I am working with an AngularJS frontend and using Express, Node, and MongoDB on the backend. My current setup is as follows: // my data to push to the server $scope.things = [{title:"title", other properties}, {title:"title", other properties}, {titl ...

Creating a hierarchical list structure from a one-dimensional list using parent and child relationships in JavaScript

I am in the process of developing a web application that requires handling nested geographical data for display in a treeview and search functionality. The initial raw data structure resembles this: id:1, name:UK id:2: name: South-East, parentId: 1 id:3: ...

What are some ways to integrate the features of ctype.h into JavaScript?

How can glibc's ctype.h be effectively translated into JavaScript? While I believe it is possible, I am struggling to locate the tables and bitshifting operations used in the C source code. What are the best techniques to employ in this situation? isa ...

Axios fails to capture and transmit data to the client's end

I created a backend using Express to retrieve Instagram feed images and then send their URLs to my front end, which is built with ReactJs. When I fetch the image URLs with instagram-node and send them to the front end, everything functions as expected. How ...

Save the altered aircraft shapes as JSON files, utilizing the Three.js framework

I've been working on modifying the vertices of a plane geometry in order to create new shapes. However, I've run into an issue where when I export the modified geometry as JSON, the changes I made to the vertices are not included in the exported ...

Having difficulty accessing and updating data in a database while using Discord.js

My goal is to enable staff to respond to the last direct message (DM) by using ~reply <message> instead of ~dm <userID> <message>. However, before I can do that, I need to store the user's ID in a database to identify the last person ...

Leverage JavaScript to showcase Django object on the webpage

I am trying to achieve the following using javascript: when a row is clicked, it should retrieve the index and display the object at that index. This functionality works in a django template. <div>{{ project.0.customer_name}}</div> <div> ...

Filtering data in AngularJS using code

I'm currently working on a project using AngularJS and I need to implement a search feature that focuses only on searching by Code. Right now, the search functionality I have searches for any input, including id, name, city, and code. How can I modify ...

Unable to find the URL with the help of a selenium web driver

I'm trying to find the location of a link labeled Taschen in this code snippet. Can you help me with that? Code: <a data-flyout-target="handbags" title="Taschen" href="#">Taschen</a> ...

What steps can I take to ensure a JavaScript loading image is displayed until the entire page has finished loading?

Looking to implement a JavaScript loading image that displays until the page has fully loaded? I'm currently developing an online antivirus scanner and in need of help. I am trying to set up JavaScript to show a loading image while a file is being up ...

Error! Element not found in cloned iframe #2460, promise unhandled

Can you help me troubleshoot this issue? This is the code I'm working with: const section = document.createElement("section"); const myHTMLCode = "<p>Greetings</p>"; section.insertAdjacentHTML("afterbegin", my ...

Leveraging Parse methods within a Node JS Cron job

My current task involves writing a Cron Job that requires the use of Parse methods. I have the following code snippet at hand: var crontab = require('node-crontab'); var jobId = crontab.scheduleJob("* * * * * *", function(){ ...

Minimizing the number of iterations in nested list loops

Struggling to optimize loop iterations. I am dealing with 2 distinct List entities public class Material { private String mtrlId; private String uomId; private String sapEndDate; } public class UnitPrice { private String unitPrice; pr ...

What could be causing the InvalidClassException to be thrown in my program when using a recursive method?

Within my program, I've created a FacebookUser class that contains an ArrayList of the user's friends. Each friend in this list can also have their own set of friends. To retrieve a new ArrayList that includes all of the user's friends, as w ...

The absence of variable declaration in a 'for...of' loop is functional in .js files but does not work in

index.js let items = [{ item: 'apple' }, { item: 'banana' }, { item: 'orange' }]; for (item of items) { console.log(item); } Execute using node $ node index.js { item: 'apple' } { item: 'banana' } { ...

Utilizing a function argument within the :not() selector

I am currently working towards the objective of selecting all elements in my document except for those within a specific class. This is what I have come up with so far: var x = document.querySelectorAll(":not(.myParameter)"); My aim is to make 'myPa ...

Issue with Bottle.py: When using AJAX, request.forms.get() is returning NoneType

Having trouble sending JavaScript data to a bottle.py server using AJAX? Despite trying numerous solutions from various sources, none seem to be working. To provide clarity, I'm focusing on the AJAX call code here. Can someone explain why request.for ...

Is there a way to determine if this particular element is the initial one with its class throughout the entire document?

Struggling to come up with a conditional to load a script. Looking for a conditional that can identify if this element is the first one in the entire document with a specific class. The issue I'm facing is that I've created a BBCode for a phpBB ...

Change the size of Jive Addon Tile in a vertical orientation

Seeking assistance with resizing the tile container in an angular application embedded within a Jive tile when the view changes. Any advice on how to tackle this issue? This particular tile is deployed to a Jive Cloud instance using a Jive add-on. ...