Skip to content

Instantly share code, notes, and snippets.

@joanllenas
Created January 7, 2018 16:06
Show Gist options
  • Save joanllenas/81c4e78ddc706f181bcf7b73fd3bb8c6 to your computer and use it in GitHub Desktop.
Save joanllenas/81c4e78ddc706f181bcf7b73fd3bb8c6 to your computer and use it in GitHub Desktop.
Elm example: Capture div click mouse coordinates
-- https://ellie-app.com/fMXwpzt7va1/1
module MouseCoordinates exposing (..)
import Html exposing (Html, div, text, program)
import Html.Attributes exposing (style)
import Html.Events exposing (on)
import Json.Decode as Decode exposing (Decoder, map2, at, int)
-- MODEL
type alias Coords =
{ offsetX : Int
, offsetY : Int
}
type alias Model =
{ x : Int
, y : Int
}
init : ( Model, Cmd Msg )
init =
( Model 0 0, Cmd.none )
-- MESSAGES
type Msg
= DivClick Coords
-- VIEW
coordsDecoder : Decoder Coords
coordsDecoder =
map2 Coords
(at [ "offsetX" ] int)
(at [ "offsetY" ] int)
view : Model -> Html Msg
view model =
div [ on "click" (Decode.map DivClick coordsDecoder)
, style [("backgroundColor", "#ccc"), ("height", "300px"), ("padding", "10px")]
]
[ text ("Click the gray area! Coords: " ++ (toString model.x) ++ ", " ++ (toString model.y)) ]
-- UPDATE
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
DivClick coords ->
( { model | x = coords.offsetX
, y = coords.offsetY
}
, Cmd.none
)
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- MAIN
main : Program Never Model Msg
main =
program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment