To listen for mouse events on an HTML element in Elm, we can use Html.Events.onClick. However, I want to listen for mouse clicks anywhere on the document.
I found the elm-lang/mouse
package that provides Mouse.clicks which seems to be intended for just that. On Elm 0.18, it can be installed like this:
elm-package install elm-lang/mouse
And imported like this:
import Mouse exposing (clicks)
But on Elm 0.19, the command
elm install elm-lang/mouse
does not work:
The following packages do not work with Elm 0.19.0 right now:
elm-lang/mouse
No reason is given in the console output. The documentation does not seem to indicate anything about this module has changed with version 0.19.
How can I install the module? Or alternatively, how can I use Elm's standard library to listen for mouse clicks globally (on the document)?
The package has been merged into elm/browser.
So rather than Mouse.clicks
, you now use Browser.Events.onClick
.
See the documentation for the browser package here.
To retrieve the mouse position, use Json.Decode:
import Browser.Events exposing (onClick)
import Json.Decode as Decode
type alias Msg =
{ x : Int, y : Int }
subscriptions : Model -> Sub Msg
subscriptions model =
onClick
(Decode.map2 Msg
(Decode.field "pageX" Decode.int)
(Decode.field "pageY" Decode.int)
)
For other attributes, see the documentation on MouseEvent.