9

How do I use preventDefault in elm? Say on a keyboard event:

keyDown keyCode model =
    case keyCode of

        13 -> -- Enter key
            model

if we don't want the default behaviour?

Html.Events has methods for it, but I don't understand how to use it in practice.

swelet
  • 8,192
  • 5
  • 33
  • 45
  • 2
    http://package.elm-lang.org/packages/evancz/elm-html/4.0.0/Html-Events#Options – Knu Aug 11 '16 at 23:40

3 Answers3

6

This answer is obsolete with Elm 0.19

Learn how to use Html.Events.on, then it becomes obvious.

myInput =
  input
    [ on "keydown" (Json.map KeyInput keyCode)]
    []
    

becomes...

myInputWithOptions =
  input
    [ onWithOptions "keydown" options (Json.map KeyInput keyCode)]
    []

options =
  { stopPropagation = True
  , preventDefault = True
  }

(Here, message constructor KeyInput is defined as: type Msg = KeyInput Int)

boxed
  • 3,895
  • 2
  • 24
  • 26
Tosh
  • 35,955
  • 11
  • 65
  • 55
6

@Tosh has shown how to stop event propagation and prevent default behaviour in his answer.

If your specific case is to prevent default behaviour only on Enter but not on any other keys, this is currently not possible in Elm—you'll have to resort to Ports and JS.

Søren Debois
  • 5,598
  • 26
  • 48
  • Looks like there's a workaround now for conditionally calling preventDefault: https://github.com/elm/virtual-dom/issues/18#issuecomment-273403774 – Jason Stallings Jun 01 '18 at 23:03
2

You can now use the library elm-community/html-extra for that, it provides you the onClickPreventDefault and onClickStopPropagation functions.

boxed
  • 3,895
  • 2
  • 24
  • 26
Rogerio Chaves
  • 2,719
  • 2
  • 25
  • 24
  • This is a long time ago, but I actually ended up implementing it in the same way. And it works. – swelet Oct 05 '17 at 12:19