Mastering the Art of Moving Sliders in an Accordion Using JavaScriptExecutor

I am facing an issue while trying to move the Slider using the DragandDropBy method. The slider seems to be moving to the wrong position consistently. I also attempted to use javascriptexecutor, however, that doesn't seem to work either.

driver.manage().window().maximize();
driver.get("http://www.globalsqa.com/demo-site/sliders/#Color Picker");

driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS );

WebElement iFrame = driver.findElement(By.cssSelector("#post-2673 > div.twelve.columns > div.newtabs.horizontal > div > div.single_tab_div.resp-tab-content.resp-tab-content-active > p > iframe"));

String sFrameContent = iFrame.getText().toString();
System.out.println("The Iframe Content is: "+sFrameContent );

driver.switchTo().frame(iFrame);

Actions action = new Actions(driver);

WebElement redSlider = driver.findElement(By.cssSelector("div#red > div"));

Thread.sleep(1000);

action.clickAndHold(redSlider).moveByOffset(90,0).release(redSlider).release().build().perform();

JavascriptExecutor jse = (JavascriptExecutor) driver;

jse.executeScript("document.getElementsByTagName('span')[0].style.left = '10.000%' ");
System.out.println("-------END--------");

driver.switchTo().defaultContent();

The above code runs without any errors, but unfortunately, the Slider does not move correctly to the desired position.

<body class="ui-widget-content" style="border:0;">
  <p class="ui-state-default ui-corner-all ui-helper-clearfix" style="padding:4px;">
    <span class="ui-icon ui-icon-pencil" style="float:left; margin:-2px 5px 0 0;"></span> Simple Colorpicker
  </p>
  <div id="red" class="ui-slider ui-corner-all ui-slider-horizontal ui-widget ui-widget-content">
    <div class="ui-slider-range ui-corner-all ui-widget-header ui-slider-range-min" style="width: 9.80392%;"></div><span tabindex="0" class="ui-slider-handle ui-corner-all ui-state-default" style="left: 9.80392%;"></span></div>
  <div id="green" class="ui-slider ui-corner-all ui-slider-horizontal ui-widget ui-widget-content">
    <div class="ui-slider-range ui-corner-all ui-widget-header ui-slider-range-min" style="width: 54.902%;"></div><span tabindex="0" class="ui-slider-handle ui-corner-all ui-state-default" style="left: 54.902%;"></span></div>
  <div id="blue" class="ui-slider ui-corner-all ui-slider-horizontal ui-widget ui-widget-content">
    <div class="ui-slider-range ui-corner-all ui-widget-header ui-slider-range-min" style="width: 23.5294%;"></div><span tabindex="0" class="ui-slider-handle ui-corner-all ui-state-default" style="left: 23.5294%;"></span></div>
  <div id="swatch" class="ui-widget-content ui-corner-all" style="background-color: rgb(25, 140, 60);"></div>

</body>

Answer №1

Avoid using JSE-type responses as they do not reflect typical user interactions. Users are more likely to click on a slider rather than set it using JavaScript. To streamline testing, consider encapsulating the slider interaction within a function as shown below:

public static void adjustSlider(int position)
{
    driver.switchTo().frame(driver.findElement(By.cssSelector("iframe.demo-frame")));
    WebElement slider = new WebDriverWait(driver, 3).until(ExpectedConditions.elementToBeClickable(By.id("slider")));
    Dimension d = slider.getSize();
    new Actions(driver).moveToElement(slider, d.width * position / 100, d.height / 2).click().build().perform();
    driver.switchTo().defaultContent();
}

Simply call the function like this:

driver.get("http://www.example.com/slider-demo");
adjustSlider(50);

It is advisable to include validation checks in your function to ensure the input position is within the valid range of 0-100.

Answer №2

If you're looking for a solution, this code should do the trick:

    JavaScriptExecutor js = (JavaScriptExecutor) driver;

    js.executeScript("document.getElementById('red').getElementsByTagName('div')[0].setAttribute('style', 'width: 50%;')");
    js.executeScript("document.getElementById('red').getElementsByTagName('span')[0].setAttribute('style', 'left: 50%;')");

UPDATE:-

You can also try the following method:

    WebElement spanButton = driver.findElement(By.cssSelector("div#red > div+span"));

            Actions action = new Actions(driver);

            action.clickAndHold(spanButton).moveByOffset(-20,0).release(spanButton).build().perform(); // to move slider backward

action.clickAndHold(spanButton).moveByOffset(20,0).release(spanButton).build().perform(); // to move slider forward

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

Is there a way I can showcase each number that is inputted into my while loop?

Develop a Java program that calculates and shows the sum of numbers inputted by the user. The summation process should continue as long as the user desires. When the program finishes, display the total sum in the following format: for example, if the user ...

What is the better option in GWT client - Java or JSON?

I'm working on a GWT client project with REST as my web service. I have a Student class that I want to save in the database which is part of the web service. Right now, I am converting the student object to JSON and sending it to the server. Is this t ...

Express receiving undefined data in Ajax POST request

I'm currently facing an issue with sending data to be parsed. The client-side script I have is as follows: function addURL(link) { console.log("Adding url..."); $.ajax({ type: "POST", url: location.protocol + "/ ...

To trigger the action of any button in Ionic/Angular, I need to double-click

I am encountering an issue with an app that I developed using the Ionic framework. While the app works perfectly on Android devices, I am facing a peculiar situation on iOS. Every time I click a button in the Simulator or on an actual iOS device, I have t ...

Methods for automating the clicking of a hyperlink within Bootstrap tabs programmatically

I am attempting to programmatically trigger a click event on a specific href link within Bootstrap tabs. For reference, here is the link to the codepen: linkToCodePen <ul class="nav nav-tabs" id="myNavTabs"> <li class="active">&l ...

Why is JSP compilation essential in achieving its goals?

At the moment, I am involved in modifying JSP and subsequently uploading it to the server for compilation. Upon compilation, a .class file is generated for the modified JSP. If I were to remove the original JSP from the server, would it still function pr ...

What is the process for establishing a reference to a property of an object in JavaScript?

Imagine you have an object structured like this: obj = {a:{aa:1}, b:2}; You decide to create a convenient variable (referred to as a pointer) named x that points to obj.a.aa with the following code: x = obj.a.aa; Next, your goal is to update the value ...

`How to handle a java.lang.NullPointerException when using Selenium with Cucumber?`

RegistrationPage.feature Feature: Registering a User Background: Given The User is on the Registration Page Scenario: User Registration Process When The User Enters Contact Information And The User Enters Mailing Information When The User Enters User Inf ...

Can you explain the meaning of classpath:/, classpath:/config/, file:./, and file:./config/ in Spring Boot?

According to the Spring boot documentation: When searching for config locations, the order is reversed. The default configured locations are classpath:/,classpath:/config/,file:./,file:./config/. This results in the following search order: 1.file:./ ...

Issue with firing the React-Redux action has been encountered

I am currently utilizing React along with react-redux, redux and redux-actions. Within my application, I have a specific action that is responsible for verifying the validity of the token stored in localStorage to ensure it is not expired. This action loo ...

What is the best way to retrieve the crash traceback in Android Studio?

Whenever my game (developed with LibGDX) crashes on either a mobile device or in a virtual environment, I encounter the following error message: at com.firstgame.game.firstGame.render(firstGame.java:20) This directs me to line 20 of my code where the pub ...

Updating the span's value with Javascript

My HTML document includes a span element that looks like this: <span class="className">0</span> and it should display: 0 The issue at hand is how to increment the value of the span (e.g. from 2 to 3) by clicking a button using JavaScript. ...

Is it possible to perform a cucumber test with variable modifications?

Let me share a snippet of code from the testing I am conducting on a school platform: Background: I Enter the school page In Schools I navigate to: | Hierarchical level | Action | Value | | District | expand ...

Reduce the number of divs on a webpage while incorporating animated transitions

I've been attempting to incorporate an animation on the width property for my div .panels. I've tried using transition-property in CSS and also with .animate() in jQuery, but unfortunately, it doesn't seem to be working. I also noticed that ...

Guide to successfully formatting and outputting JSON on a Jersey RESTful web service

After incorporating a Jersey library and a media JSON library into my application, the XML configuration looks like this: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3. ...

Refreshed page causing hide/show div to reset

Hello there, I'm currently working on a web application and I need to implement some JavaScript code. The application consists of three sections, each with its own title and button. When the button is clicked, a hidden div tag is displayed. Clicking t ...

What is the best way to identify when a particular character has been entered into the input field?

HTML <div class="form-group"><label class="col-md-4 control-label" for="s1">URL</label> <div class="col-md-4"><input id="url" name="url" type="text" ng-change="checkVal()" ng-model="url" placeholder="" class="for ...

Guide: Utilizing ng-repeat in Ionic framework for displaying nested JSON objects

Currently in the process of developing a basic hybrid mobile application using the Ionic framework. The main functionality involves sending a GET request to retrieve matching last names when searched for, and then displaying their corresponding ID's. ...

What is the best way to prevent elements in the split function from being stored in an array?

Currently, I am attempting to utilize the split() method in Javascript to split elements into an array, a result that I do not desire. My goal is for the elements to be stored as values within an object. var string = "as1234,as5678,as6789"; var result = ...

What is the best overlay to utilize for developing Java games?

I am currently working on creating a Java game that is 2D and doesn't require a lot of complex logic. I am debating whether I should use JFrame, JPanel, or Canvas for this project. Are there any advantages to using one over the others? ...