We can use the HTML DOM
click() method to simulate the onClick event of an HTML button.
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.
Our implementation includes the following:
onmouseover event of the button by attaching the
change() function to it.
change() method, get reference to the button via
click() method on the referenced button.
onClicked event of the button by attaching the
clicked() function to it.
clicked() changes the innerHTML of the paragraph
To view the output, hover your mouse over the “Don’t click” button in the right panel of the following widget.
In line 6, we add an empty paragraph with ID
In line 7, we add a button with ID
add. The button’s
onClick event is bound to the
clicked event. The button’s
onmouseover event is bound to the
In line 16,
document.getElementById("add") to get the element and apply the
click() method. As a result, the
clicked() function is called.
In line 13, the
clicked() method calls
document.getElementById("elem") and sets
innerHtml to “Clicked”.
View all Courses