jquery Event Listener on DropDown Open

Watte picture Watte · Jan 15, 2016 · Viewed 15.8k times · Source

Having this simple dropdown menu:

<select id="foo">
   <option>bar</option>
</select>

And an jQuery listener initialization like this:

$("#foo").on("click", function() {
    console.log("stuff");
});

The event is only fired when the user closes the drop down, either by selecting an option or by clicking outside of the box. Is there any way to get the event, when he opens the box?

Answer

Vahid Msm picture Vahid Msm · Jan 15, 2016

The right event for this purpose is change click together and will get fire every time that select input changed or clicked.

$("#foo").on("click change", function(e) {
    $("#output").html("Event type: " + e.target.nodeName);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="foo">
   <option value="1">foooo</option>
   <option value="2">bar</option>
</select>

<div id="output"></div>