Detect input events for things like text fields or text areas.
For more details on how onInput works, check out targetValue.
Note 1: It grabs the string value at event.target.value, so it will
not work if you need some other information. For example, if you want to track
inputs on a range slider, make a custom handler with on.
Note 2: It uses stopPropagationOn internally to always stop propagation
of the event. This is important for complicated reasons explained here and
here.
Detect change
events on checkboxes. It will grab the boolean value from event.target.checked
on any input event.
Check out targetChecked for more details on how this works.
Detect a submit
event with preventDefault
in order to prevent the form from changing the page’s location. If you need
different behavior, create a custom event handler.
Create a custom event listener. Normally this will not be necessary, but
you have the power! Here is how onClick can be defined for example:
import Json.Decode as Decode
onClick : msg -> Element msg -> Element msg
onClick message =
Events.on "click" (Decode.succeed message)The first argument is the event name in the same format as with JavaScript's
addEventListener function.
The second argument is a JSON decoder. Read more about these here.
When an event occurs, the decoder tries to turn the event object into an Elm
value. If successful, the value is routed to your update function. In the
case of onClick we always just succeed with the given message.
If this is confusing, work through the Elm Architecture Tutorial. It really helps!
Note: This creates a passive event listener, enabling optimizations for touch, scroll, and wheel events in some browsers.
Create an event listener that may stopPropagation. Your decoder
must produce a message and a Bool that decides if stopPropagation should
be called.
Note: This creates a passive event listener, enabling optimizations for touch, scroll, and wheel events in some browsers.
Create an event listener that may preventDefault. Your decoder
must produce a message and a Bool that decides if preventDefault should
be called.
For example, the onSubmit function in this library always prevents the
default behavior:
onSubmit : msg -> Element msg -> Element msg onSubmit msg = Events.preventDefaultOn "submit" (Json.map alwaysPreventDefault (Json.succeed msg))
alwaysPreventDefault : msg -> ( msg, Bool )
alwaysPreventDefault msg =
Html.Events.alwaysPreventDefault msg
|> Shared.addAttribute
( msg, True )Create an event listener that may stopPropagation or
preventDefault.
Note: Check out the lower-level event API in elm/virtual-dom for more
information on exactly how events work, especially the Handler
docs.