Trigger events
The trigger is the component in charge of opening and closing the dropdown
(although it also closes if you click outside it). By default the event that
to which the trigger reacts is the
click
event.
You can change that passing the
eventType="mousedown"
to the trigger. Check below for both approaches. The difference is subtle.
This does not affect to the behavior of the dropdown on touch devices. On
mobile or tablets the dropdown automatically depends on the
"touchend"
event.
Event handlers
As with any regular HTML element, you can attach events to the trigger using
the
{{on}}
element modifier. The events you subscribe to using this approach will aways
run before the default events that this component attaches, giving you a
chance to prevent the default behavior by calling
event.stopImmediatePropagation()
.
What can you do with this? Let's see some examples.
{{on "keydown"}}
One real world situation where I found this to be necessary, is when you want to open the dropdown with a key that usually does not open it, like by example the arrow keys.
As with any other event, calling
e.stopImmediatePropagation()
will stop the default handler from running, so you can use this action to
prevent the
space,
enter
and
esc
keys from doing what they do by default.
{{on "click"}}
The
click
event is the one that usually opens the dropdown, but you can pass your own
function.
Good examples of this are preventing the component from opening with the mouse and/or react in some way to those attempts.
{{on "touchend"}}
Exactly identical to
{{on "click"}}
but for touch screens. I'm not even going to create another example.
{{on "mouseenter"}} / {{on "mouseleave"}}
I use this event to open the dropdown when you hover it and close it when you leave but you can really use it a lot more.
By example, imagine that a dropdown is disabled and you want to highlight some other element in the form that the user must enable first.
{{on "focus"}}/{{on "blur"}}
I've used this two events in conjuntion to style a parent element while some
of the components inside it have the focus, achieving a poor mans' version of
the upcoming CSS
:focus-within
pseudo selector.
Focus alternatively the input and the button next to it
This is the most involved example yet. Both the text input and the trigger are focusable on their own, but by tracking when they get and loose the focus we simulate that the entire input-group is focused, which would be impossible just just CSS today.
Right now this behavior cannot be achieved across browsers without some help from javascript.
Those are just some examples of the kind of behaviors you can implement adding custom events to the trigger.