LoginSignup
2
0

More than 1 year has passed since last update.

Elmでマウスの右クリックを検知する

Last updated at Posted at 2022-12-08

Elmでマウスの右クリックを検知するにはどうすれば?と思って調べた際のメモ。

mpizenberg/elm-pointer-events を使うのが楽そう。

左クリックor右クリックをボタンのテキストに表示するサンプルコード
module Main exposing (main)

import Browser
import Html exposing (Html, button, div, text)
import Html.Events.Extra.Mouse as Mouse

type alias Model = { buttonText : String }

type Msg = LeftClick | RightClick

initialModel : Model
initialModel =
    { buttonText = "Clicked: -" }

update : Msg -> Model -> Model
update msg model =
    case msg of
        LeftClick ->
            { model | buttonText = "Clicked: Left" }

        RightClick ->
            { model | buttonText = "Clicked: Right" }

view : Model -> Html Msg
view model =
    div []
        [ button
            [ Mouse.onClick (\_ -> LeftClick)
            , Mouse.onContextMenu (\_ -> RightClick)
            ]
            [ text model.buttonText ]
        ]

main : Program () Model Msg
main =
    Browser.sandbox
        { init = initialModel
        , view = view
        , update = update
        }

実際のアプリ(Ellie)

2022.12.10 追記

@ababup1192 さんから Html.Events.custom でいけますよとのこと。

折角なので実装してみましょう。

Html.Events.custom版
module Main exposing (main)

import Browser
import Html exposing (Attribute, Html, button, div, text)
import Html.Events as Events
import Json.Decode as JD

-- (略)

view : Model -> Html Msg
view model =
    div []
        [ button
            [ Events.onClick LeftClick
            , Events.custom "contextmenu" <|
                JD.succeed
                    { message = RightClick
                    , stopPropagation = True
                    , preventDefault = True
                    }
            ]
            [ text model.buttonText ]
        ]

-- (略)

実際のアプリ(Ellie)

OK👍

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0