Mouse hover and other mouse events in WebDriver

This is widely known issue among web driver community, how to perform mouse hover.  I have many scenarios in my test where I needed to perform mouse hover to see calendar, email schedule etc. After many attempts, I found solution which is actually working very well for me but I am not sure if it’s going to work with your application of not.  Before going into coding we need to consider few limitations,

  • In Firefox, you have to maximize the webpage just before doing mouseover to get the focus on browser.
  • Works fine even in normal window size with other browser like IE and Chrome.



For mouse event, you  can call Action builder or even java script can do as well. I will not go in more theoretical detail but directly into coding. I am giving the same code I am using in my scripts, so please feel free to change or modify as per your need.

Using Action Builder:

public static bool ElementMouseOver(IWebElement targetElement)
        {
            Size currentWinSize = _driver.Manage().Window.Size;
            _driver.Manage().Window.Maximize();
            OpenQA.Selenium.Interactions.Actions builder = new OpenQA.Selenium.Interactions.Actions(_driver);
            try
            {
                builder.MoveToElement(targetElement).Build().Perform();
                Thread.Sleep(2000);//2 sec is just to for this blog.
                                   //I use custome method to wait element being appeared after mouse hover event.
                                   //You can use other variable wait time but make sure your give some pause
                                   //otherwise mouse hover will happen for fraction of seconds and then disappear.

                _driver.Manage().Window.Size = currentWinSize;
            }
            catch (Exception e)
            {
                loggerInfo.Instance.Message(e.Message);
                return false;
            }
            return true;
        }



Using JavaScript

public static void MouseHoverByJavaScript(IWebElement targetElement)
        {

            string javaScript = "var evObj = document.createEvent('MouseEvents');" +
                                "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);" +
                                "arguments[0].dispatchEvent(evObj);";
            IJavaScriptExecutor js = _driver as IJavaScriptExecutor;
            js.ExecuteScript(javaScript, targetElement);
          }

You can use above java script to perform other  mouse events like click/double click. Please refer initMouseEvent which you can use in above code.
                          
I implemented drag and Drop event as well using Action builder itself.
Drag And Drop


            IWebElement source = FindElement("blah blah");
            IWebElement target = FindElement("blah blah");
            OpenQA.Selenium.Interactions.Actions builder = new OpenQA.Selenium.Interactions.Actions(_driver);
            try
            {
               builder.DragAndDrop(source, target).Build().Perform();
            }
            catch (Exception e)
            {
                //log Exception.I use NLog.
            }

Everyone uses own approach to handle such events. I mostly use Firefox/Chrome for testing as IE some time very flaky. And personally I hate IE. I tested above code in FF/Chrome and it was working fine. I would like to learn new way to handle such events If you are aware of any and please don’t forget to post in comment below or email me via contact us page.

12 Comments

  • samwoo111

    October 4, 2012

    I ran into a case where when I drag and drop I have to put a short sleep after moving the mouse and releasing the mouse button. To fix the issue I changed my DragAndDrop function to do this:

    Actions builder = new Actions(WTWebUiAuto.webDriver);
    builder.ClickAndHold(source);
    builder.MoveToElement(target, xOffset, yOffset);
    builder.Perform();

    Thread.Sleep(delayBeforeDropping);
    Actions builder2 = new Actions(WTWebUiAuto.webDriver);
    builder2.Release();
    builder2.Perform();

    Reply
  • samwoo111

    October 4, 2012

    And thanks, your mouseover methods helped fix an issue I was seeing sometimes in firefox.

    Reply
  • admin

    October 5, 2012

    Thanks samwoo111 for your comments. I am very glad that above code helped you!.

    Reply
  • Deepak

    January 22, 2015

    GREAT lines of code.
    Solved my problem
    Thanks a lot

    public static void MouseHoverByJavaScript(IWebElement targetElement)
    {

    string javaScript = “var evObj = document.createEvent(‘MouseEvents’);” +
    “evObj.initMouseEvent(\”mouseover\”,true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);” +
    “arguments[0].dispatchEvent(evObj);”;
    IJavaScriptExecutor js = _driver as IJavaScriptExecutor;
    js.ExecuteScript(javaScript, targetElement);
    }

    Reply
  • surekha

    July 8, 2015

    i need mouse hover code for python not java and also for Interent explorer browser .Please provide solution .It may great help for us.

    Reply
    • Aditya

      July 9, 2015

      Hi Surekha,
      Try this
      from selenium.webdriver.common.action_chains import ActionChains

      def hover(self):
      wd = webdriver_connection.connection
      element = wd.find_element_by_link_text(self.locator)
      hov = ActionChains(wd).move_to_element(element)
      hov.perform()

      if this doesn’t work, please post your question in http://learnseleniumtesting.com/forum/

      Reply
  • Sreekanth

    September 2, 2015

    Hi,
    I am running the selenium scripts on Safari browser but its doesnt support interaction API. can you please send me the workaround javascript code for the below code please.

    Actions action = new Actions(driver);
    action.moveToElement(element);
    action.clickAndHold();
    action.moveByOffset(100,200).moveByOffset(-10, -20).moveByOffset(-10, -10).moveByOffset(-10, -20).build().perform();
    action.release().build().perform();

    Reply
  • Sonali

    September 25, 2015

    Hey Aditya,
    Your code has really helped me.
    Thanks a lot :)

    Reply
    • Aditya

      September 25, 2015

      Thanks Sonali,
      Glad that code was helpful.

      Reply
  • Mohit

    March 3, 2016

    The below mouse action code has worked for me while selecting a value from a drop-down :
    Actions act = new Actions(driver);
    act.moveToElement(driver.findElement(By.xpath(“”))).perform();
    act.moveByOffset(10, 0);(driver.findElement(By.xpath(“element path”))).click();

    Reply
  • Raveendra

    April 7, 2016

    How i need to copy the text of the field once Hover on element.?

    Reply
    • Aditya

      April 7, 2016

      Raveendra,
      Once you hover the mouse over the element, you just need to read that items in the same way you read other element. I think you are talking about some special case. Please share the issue with example.

      Reply

Leave a Reply