Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

html
javascript
communitycreator

How to trigger onClick from HTML button’s mouseOver event

Ayush Trivedi

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:

  1. Hook the onmouseover event of the button by attaching the change() function to it.

  2. From the change() method, get reference to the button via document.getElementById().

  3. Call the click() method on the referenced button.

  4. Hook the onClicked event of the button by attaching the clicked() function to it. clicked() changes the innerHTML of the paragraph elem to Clicked.

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’s onClick event is bound to the clicked event. The button’s onmouseover event is bound to the change() function.

    • In line 16, change() uses 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”.

    RELATED TAGS

    html
    javascript
    communitycreator
    RELATED COURSES

    View all Courses

    Keep Exploring