Search code examples
elm

Access attribute name with on "click" event handler


I am trying to access an elements HTML properties when clicked. I figured out that Events.onClick will only return event.target.value and I need to use Events.on to handle custom behaviours.

What I need is: when click on a div I should be able to access its HTML properties, for now id and name and send this value to update with some message.

I tried like this:

onClickData : msg -> Attribute msg
onClickData handler =
    on "click" (Decode.succeed handler )
---
view: ...
    ....
    div[onClickData HandleClick] []

This way i am able to trigger HandleClick action when the div is clicked but cannot access its HTML properties.


Solution

  • As @glennsl has noted, you normally would want to do something more like this:

    view identification =
        button [ id identification, onClick (MyMsg identification) ] 
            [ text "Click me" 
            ]
    

    i.e. you can pass data straight into your Msg type.


    That said, there are some unusual inter-op situations where you might want to do this. The general principle is that you can get the element that you bound your event handler to from event.currentTarget, so you can use the following decoder:

    decodeProperty : String -> Decoder a -> Decoder a 
    decodeProperty property decoder = 
       Decode.at ["currentTarget", property] decoder
    
    
    --- use
    
    onClickId : (String -> msg) -> Attribute msg
    onClickId tagger =
        on "click" (Decode.map tagger (decodeProperty "id"))