getting x/y position of click event within an element

1,132 views
Skip to first unread message

Aaron VonderHaar

unread,
Jun 10, 2015, 2:25:03 AM6/10/15
to elm-d...@googlegroups.com
Does anyone have a good example of getting the x/y coordinates of a mouse click relative to the element being clicked when using elm-html?

mbox : Mailbox (Int,Int)
mbox = Signal.mailbox (0,0)

view : Html
view = Html.div [ Html.onClick mbox.address (x,y) ] []

I'd like (x,y) to be the location of the click, relative to the div itself.

Richard Feldman

unread,
Jun 10, 2015, 12:05:53 PM6/10/15
to elm-d...@googlegroups.com
You should be able to decode it out of the click event. I forget which of the fields on the event gives you the x and y relative to the element, but I believe that's where you want to look.

Evan Czaplicki

unread,
Jun 10, 2015, 12:24:52 PM6/10/15
to elm-d...@googlegroups.com
Yeah, use Html.on instead of Html.onClick. The more generic version gives you access to all the info in the event.

On Wed, Jun 10, 2015 at 9:05 AM, Richard Feldman <richard....@gmail.com> wrote:
You should be able to decode it out of the click event. I forget which of the fields on the event gives you the x and y relative to the element, but I believe that's where you want to look.

--
You received this message because you are subscribed to the Google Groups "Elm Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elm-discuss...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Aaron VonderHaar

unread,
Jun 10, 2015, 4:23:47 PM6/10/15
to elm-d...@googlegroups.com
Great, thanks.  Html.on "click" ... works!

It seems that the correct way to do this in javascript is `event.pageX - $(element).offset().left`, where offset().left is the sum of element.offsetLeft for the element and it's chain of element.offsetParent nodes.

I've written the following decoder to pull this out (it's currently incomplete, since it doesn't deal with offsetParent yet, but I can see that it would be doable to add that).

import Json.Decode as Decode
 
decodeClickLocation : Decode.Decoder (Int,Int)
decodeClickLocation =
Decode.object2 (,)
(Decode.object2 (-)
(Decode.at ["pageX"] Decode.int)
(Decode.at ["target", "offsetLeft"] Decode.int)
)
(Decode.object2 (-)
(Decode.at ["pageY"] Decode.int)
(Decode.at ["target", "offsetTop"] Decode.int)
)
Reply all
Reply to author
Forward
0 new messages