How to trigger onClick from HTML button’s mouseOver event
We can use the HTML DOM click() method to simulate the onClick event of an HTML button.
When the click() method is called on a button, it behaves exactly the same way as if the user manually clicks it with a mouse.
In the example below, we will use the onmouseover event to simulate onClick for a button. Our goal is to automatically trigger the onClick event of the button when the user hovers over it.
Strategy
Our implementation includes the following:
-
Hook the
onmouseoverevent of the button by attaching thechange()function to it. -
From the
change()method, get reference to the button viadocument.getElementById(). -
Call the
click()method on the referenced button. -
Hook the
onClickedevent of the button by attaching theclicked()function to it.clicked()changes the innerHTML of the paragraphelemtoClicked.
Code
To view the output, hover your mouse over the “Don’t click” button in the right panel of the following widget.
Explanation
-
In line 6, we add an empty paragraph with ID
elem. -
In line 7, we add a button with ID
add. The button’sonClickevent is bound to theclickedevent. The button’sonmouseoverevent is bound to thechange()function. -
In line 16,
change()usesdocument.getElementById("add")to get the element and apply theclick()method. As a result, theclicked()function is called. -
In line 13, the
clicked()method callsdocument.getElementById("elem")and setsinnerHtmlto “Clicked”.