Pausing briefly after selecting an element with Webdriver

I have been attempting to highlight an element on a webpage for a specific duration of time, approximately 5-6 seconds. However, I am facing difficulty in making the highlight persist for the desired duration as it currently flashes briefly. Despite using thread.sleep(), I have not been successful in achieving the extended highlight duration.

Is there a way to implement a conditional wait for the highlighting effect by utilizing Explicit wait or any alternative method?

Below is the snippet of code responsible for highlighting the element:

import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class HighlightElement {
public WebDriver driver;
private String baseUrl;

public static void main(String[] args) {
    HighlightElement obj=new HighlightElement();
    obj.func();
    // TODO Auto-generated method stub

}
public void func(){
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

baseUrl="http://www.creativebloq.com/netmag/get-started-django-7132932";
driver.get(baseUrl);

WebElement ele=driver.findElement(By.xpath("//*[@id='main-  content']/section/article/div/div/figure[1]/img"));
highlightElement(driver, ele);
try {
    Thread.sleep(5000);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}

public void highlightElement(WebDriver driver, WebElement element) {
for (int i = 0; i < 2; i++)
{
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "color: yellow;  border: 2px solid yellow;");
js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "");
}}
}

I also experimented with incorporating the sleep method within the highlightElement() function without success in extending the duration of the highlight effect.

Answer №1

Have you considered trying a solution similar to the following?

public void highlightElement(Driver, IWebElement element) 
    {
        for (int i = 0; i < 2; i++)
        {
            IJavaScriptExecutor js = (IJavaScriptExecutor) Driver;
            js.ExecuteScript("arguments[0].setAttribute('style', arguments[1]);", element, "color: yellow;  border: 2px solid yellow;");
            if (element.GetAttribute("style") != null)
            {
                Thread.Sleep(5000);
            }
            js.ExecuteScript("arguments[0].setAttribute('style', arguments[1]);", element, "");
        }
    }

My implementation is in C#. However, it should be relatively simple to convert to your desired language. If I interpreted your question correctly, this code snippet should do the trick.

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

Switching PHP include on an HTML page using JavaScript

I've been attempting to modify the content of the div with the ID "panel_alumno" using a JavaScript function that triggers when a button is clicked. My goal is to display a different table each time the button is pressed, but so far, I haven't be ...

Using Selenium to take screenshots of content displayed on dual monitors

I have a computer with dual monitors and I want to capture screenshots from both screens. The code I am currently using only captures the screen from the first monitor, not the second. public void takeScreenshotOfBothMonitors(String filename) throws IOExc ...

Adding content to a paragraph using Jquery

I have 4 sets of data associated with a click-bind event. My goal is to retrieve the value from a hidden field in each set and display it in a paragraph elsewhere on the page when the corresponding checkbox is clicked. Currently, I'm focused on gettin ...

In Javascript, async functions automatically halt all ongoing "threads" when a new function begins

I have a dilemma with multiple async functions that can be called by the user at any point in time. It is crucial for me to ensure that all previously executed functions (and any potential "threads" they may have initiated) are terminated when a new functi ...

What's the simplest method for updating a single value within a nested JSON object using TypeScript?

Using TypeScript version ^3.5.3 Consider the following JSON data: const config = { id: 1, title: "A good day", body: "Very detailed stories" publishedAt: "2021-01-20 12:21:12" } To update the title using spread synta ...

NextAuth encountered a CLIENT_FETCH_ERROR error while processing the session callback

Encountering issues while trying to set up nextauth v4. Keep getting this error: Client fetch error, Unexpected end of JSON input {error: {…}, path: 'session', message: 'JSON.parse: unexpected end of data at line 1 column 1 of the JSON d ...

Calculate the total sum by adding the values of the radio buttons that have been selected and then display or

Seeking help to troubleshoot my code! I want to calculate the sum of selected radio button values and display it at the end. Can anyone assist me with this issue? Thanks in advance! <html> <head> </head> <script type="text/javas ...

Discovering child elements within an iframe using Angular and customizing their appearance

Is there a simple and effective way to locate child nodes within an iframe using Angular in order to access the HTML element? Currently, I have implemented the following method: I designated a reference variable within my iframe (#privacyPolicy) <ifra ...

Execute PHP script through jQuery request within the context of a Wordpress environment

I want to replicate a specific functionality in WordPress. In this functionality, jQuery calls a PHP file that queries a MySQL table and returns the result encapsulated within an HTML tag. How can I achieve this? <html> <head> <script ...

Mastering the art of updating objects with React's useState() function

Having trouble updating my state using useState(). Whenever the alert pops up, it shows the initial value of my state. Below is a sample code snippet. I expect that when I click the Save button, setData should update data with the new form values, then di ...

Gathering partial data from shopee.co.id with the help of BeautifulSoup and Selenium

I am currently working on scraping data from shopee.co.id using beautifulsoup and selenium. I am facing an issue where I am only able to extract 42 out of 60 products from a single search results page. Could someone please provide guidance on how to modify ...

Angular implementing a carousel feature using the ngFor directive

Currently, I am working on implementing a carousel feature. The images in the carousel are sourced from a string array and I want to be able to cycle through them when clicking on the left or right arrows. How can I achieve this functionality using only ...

Executing JavaScript code using an HTML form submission

Greetings, I have implemented an HTML form on my website for user login using AJAX (jQuery), but I am encountering some issues. Below is the JavaScript code: function validateLoginDetails() { $('[name=loginUser]').click(function() { ...

Symfony's DataTables is encountering an issue with the JSON response, showing

I have encountered an issue while trying to fetch data from a response within my template table (using DataTables). The error message I receive is as follows: DataTables warning: table id=example - Invalid JSON response. For more information about this ...

Deleting lines from JSON object using Angular or JavaScript

On my webpage, I have a list where you can add a new line by pressing the "+" button (easy with push), but I'm not sure how to remove lines using the "X" button. https://i.stack.imgur.com/nm06A.png This is the JSON structure: "priceExtra" : [ ...

Stop the inheritance of CSS and JavaScript in ASCX files

Currently, I have an application that consists of only one aspx page called Default.aspx. This page dynamically loads .ascx controls as required, all of which utilize the same JS and CSS file. I am now considering implementing Bootstrap on specific control ...

Activate the class only on the current element

I need help with a specific functionality on my website. I have multiple sections with content and buttons, and when a button is clicked, I want to add an active class to the corresponding content section within the same row. <div id="1" class="row"> ...

struggling to extract specific text using Python and Selenium

I need to extract Finance data from a particular div, but there is no specific identifier for it. My current approach involves collecting 3-4 divs and checking if the word FINANSE is present in the text. If it is, I retrieve the inner div text. However, th ...

Tips for accessing a variable value within a JavaScript function

I am currently facing an issue where I am unable to retrieve a variable from a JavaScript function and use it outside of the function. While I can successfully output the variable value inside the function, I am struggling to access it elsewhere in my sc ...

What could be causing selenium to malfunction on my Mac system?

My Python 3 and Selenium 2.53.6 setup on Mac is opening Firefox, but not navigating to the specified page. I'm attempting to open "inventwithpython.com", but all that happens is Firefox launches with an error message. Here's the code snippet cau ...