Suppose I have a form with a number of components. I'd like to detect a los of focus from the group. So, focus from 1 input to another on the same form should be ignored. How can I achieve this?
First, we want to be able to tag each focusable element within the group with some attribute, so when we switch elements we'll know if we're in the same group or not. This can be achieved with data attributes.
groupIdAttribute groupId =
Html.Attributes.attribute "data-group-id" groupId
Next, we need to decode the event payload on an onBlur
event to see if the target
is different from the relatedTarget
(that which will get the focus). And report the change. (note that here we refer to data-group-id
via the path "dataset", "groupId"
)
decodeGroupIdChanged msg =
Json.Decode.oneOf
[ Json.Decode.map2
(\a b ->
if a /= b then
Just a
else
Nothing
)
(Json.Decode.at [ "target", "dataset", "groupId" ] Json.Decode.string)
(Json.Decode.at [ "relatedTarget", "dataset", "groupId" ] Json.Decode.string)
, Json.Decode.at [ "target", "dataset", "groupId" ] Json.Decode.string
|> Json.Decode.andThen (\a -> Json.Decode.succeed (Just a))
]
|> Json.Decode.andThen
(\maybeChanged ->
case maybeChanged of
Just a ->
Json.Decode.succeed (msg a)
Nothing ->
Json.Decode.fail "no change"
)
Now we can create an onGroupLoss
listener:
onGroupFocusLoss msg =
Html.Events.on "blur" (decodeGroupIdChanged msg)
And rig it up like so:
input [onGroupFocusLoss GroupFocusLoss, groupIdAttribute "a"]
Here is an example (note that it is built with elm-ui so there's a little extra code.)
https://ellie-app.com/3nkBCXJqjQTa1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With