Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I listen for global mouse events in Elm 0.19?

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)?

like image 999
Dragno Avatar asked Dec 21 '25 04:12

Dragno


1 Answers

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.

Quick online demo for click and move.

like image 123
O.O.Balance Avatar answered Dec 24 '25 11:12

O.O.Balance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!