Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery trigger("click") not working [duplicate]

Can someone please explain what is wrong with the pasted code. It shows alert on hover but does not perform click event like I expect, and click does not work on either <a> tag or <select> tag. My purpose is to expand the select element on hover by triggering click event

<!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>

<body>
    <a id="linkElement" href="www.google.co.uk">click</a>

    <select name="cars" id="selectElemet">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="fiat">Fiat</option>
      <option value="audi">Audi</option>
    </select>


    <script>
        $(document).ready(function () {
            $("#selectElement").mouseover(function () {
                $("#selectElement").trigger("click");
            });

            $("#linkElement").mouseover(function () {
                alert('here');
                $("#linkElement").trigger("click");
            });
        });
    </script>
</body>

</html>
like image 670
Frankenstine Joe Avatar asked Mar 31 '17 05:03

Frankenstine Joe


1 Answers

.trigger("click") will not actually click the element, it will only trigger click handler attached with the element. Since you have not attached any none is triggered.

You can use native .click()

$("#selectElement").get(0).click(); //get(0) returns reference to DOM element
like image 122
Satpal Avatar answered Sep 22 '22 05:09

Satpal