~ read.

Moving slider and dragging elements with WebDriver

Recently i faced with a situation where i had to automate moving ajax slider to the left and right with WebDriver. Googling this situation brought me to working code and some conclusions :

  • If you want to move slider ( both horizontal and vertical) , you can use this method:
/**
     * A convenience method that performs 
     click-and-hold at the location of the source element, 
     moves by a given offset, then releases the mouse.
     * @param slider webElement
     * @param xOffset - horizontal move offset. 
       Positive value means moving to the right, 
        negative - to the left
     * @param yOffset - vertical move offset. 
     Positive value means moving up, negative - down
     * @throws Exception
     */
    public void dragSlider(WebElement slider, int xOffset, int yOffset) 
    throws Exception {
        Actions moveSlider = new Actions(driver);
        Action action = moveSlider.clickAndHold(slider)
                .moveByOffset(xOffset, yOffset)
                .release()
                .build();
        action.perform();
        Thread.sleep(500);
    }
  • In case if you want to drag element from one position to another, you can use this method:
/**
     * @param element webElement
     * @param xOffset - horizontal move offset. 
       Positive value means moving to the right, 
       negative - to the left
     * @param yOffset - vertical move offset. 
       Positive value means moving up, 
       negative - down
     * @throws Exception
     */
    public void dragAndDrop2(WebElement element, int xOffset, int yOffset) 
    throws Exception {
        Actions builder = new Actions(driver);
        Action dragAndDrop = builder.dragAndDropBy(element, xOffset, yOffset) .build(); 
        dragAndDrop.perform();
    }

Another variation of this methods is when you're using not offset parameters, but locators for start and end points between which you want to move your element.

comments powered by Disqus
comments powered by Disqus