JavaScript - click() method

revision:


Category : element

The click() method simulates a mouse-click on an element. This method can be used to execute a click on an element as if the user manually clicked on it.

When click() is used with supported elements (such as an <input>), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.

Syntax :

        element.click()
    

Parameters: none

Examples:

            <form>
                <input type="checkbox" id="myCheck" onmouseover="myFunction()"
                  onclick="alert('click event occurred')" />
              </form>
              <script>
                // On mouse-over, execute myFunction
                function myFunction() {
                document.getElementById("myCheck").click();
                }
              </script>
        

Practical examples

example: hover over the checkbox to simulate a mouse-click
code:
                    <div>
                        <form>
                            <input type="checkbox" id="myCheck" onmouseover="hoverFunction()">
                        </form>
                    </div>
                    <script>
                        function hoverFunction() {
                        document.getElementById("myCheck").click();
                        }
                    </script>
                

example: the element.click() method triggers a click event on the specified element.

Hover me to click on the button

code:
                    <div>
                        <p onmouseover="clickButton()">Hover me to click on the button</p>
                        <button onclick="myFunction()">Click Me</button>
                        <p id="point"></p>
                    </div>
                    <script>
                        var x = document.getElementById("point");
                        var elem = document.getElementsByTagName("button")[0];
                        var count = 0;
                        function clickButton(){
                        elem.click();
                        }
                        function myFunction(){
                            count += 1;
                            x.innerHTML = "You clicked the button " + count +" time(s)"; 
                        }
                    </script>