Skip to content

Instantly share code, notes, and snippets.

@ali-abrar
Last active December 26, 2020 01:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ali-abrar/f4c1e43d554f3a1fa28d9f3097120807 to your computer and use it in GitHub Desktop.
Save ali-abrar/f4c1e43d554f3a1fa28d9f3097120807 to your computer and use it in GitHub Desktop.
reflex-dom <body> key handler
{-# language PackageImports #-}
import Control.Monad
import "ghcjs-dom" GHCJS.DOM.Document (getBody)
import GHCJS.DOM.EventM (on, preventDefault)
import GHCJS.DOM.GlobalEventHandlers (keyDown)
import Reflex.Dom hiding (preventDefault)
import Web.KeyCode
main :: IO ()
main = mainWidget $ do
doc <- askDocument
mbody <- getBody doc
forM_ mbody $ \body -> do
kp <- wrapDomEvent body (`on` keyDown) $ do
preventDefault -- This 'preventDefault' is here to prevent
-- the browser's default behavior when keys
-- like <F1> or the arrow keys are pressed.
-- If you want to preserve default behavior
-- this can be removed, or you can apply it
-- selectively, only to certain keypresses.
i <- getKeyEvent
return i
lastKeyPressed <- holdDyn Nothing $
Just . keyCodeLookup . fromEnum <$> kp
display lastKeyPressed
@ali-abrar
Copy link
Author

Revision #2 of this gist has been tested against reflex-platform v0.6.2.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment