6

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?

Davis Broda
  • 4,102
  • 5
  • 23
  • 37
Watte
  • 192
  • 1
  • 4
  • 14
  • Possible duplicate of [Is there a DOM event that fires when an HTML select element is closed?](http://stackoverflow.com/questions/6207929/is-there-a-dom-event-that-fires-when-an-html-select-element-is-closed) – epoch Jan 15 '16 at 11:59
  • 1
    Yeah thats kinda the same question. Accepted answer uses mousedown events, which isnt that pretty, but I guess I / we have to deal with it. Thanks so far! – Watte Jan 15 '16 at 15:35
  • I'm going with `focus`. Not entirely what I want, but close enough. – aross Nov 16 '17 at 12:47

3 Answers3

4

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>
Vahid Msm
  • 1,032
  • 7
  • 16
  • The "change" event fires when you really "change" (haha.. sry) something. E.g. Instead of "bar" you select "things". But it does not fire when you select "bar" when "bar" is already select, or if you even open the dropdown. – Watte Jan 15 '16 at 15:32
  • @Watte So i updated the code to fire ```change``` and ```click``` together, is this what u want? – Vahid Msm Jan 15 '16 at 15:44
  • Event does not fire when opening the menu. Firefox Developer Edition 68.0b10 – stef Jun 20 '19 at 21:24
2

Try events:

show.bs.dropdown

shown.bs.dropdown

https://getbootstrap.com/docs/4.0/components/dropdowns/#events

Giulio Caccin
  • 2,962
  • 6
  • 36
  • 57
0
    $(document).on('focus', '#foo', function () {
        console.log('Dropdown Open');
    });

Works for me !!

xyz
  • 405
  • 1
  • 6
  • 19