3

I'm using purescript-halogen to build a spreadsheet-like table (similar to Handsontable). If you double-click a cell, an html input element is rendered as a child of the respective table cell (and no such element is rendered for all the other cells).

This works really well with halogen, except that I don't know how to automatically set the focus to the newly created input element.

I tried the autofocus attribute, but this only works for the first cell that is double-clicked. The JavaScript way to do it is by calling the focus() method on the new element, but I don't know how to call it after the DOM has been updated in halogen. Any ideas?

1
  • 2
    Perhaps you want to use an "initializer"? The function signature changed in the new version, but if you look up that name in the docs/examples, you should find it. Commented Aug 27, 2015 at 16:03

2 Answers 2

5

Ok, here is how I did it using Phil's Initializer hint:

Write a JavaScript function that actually focuses the element.

exports.setFocusImpl = function(elemId) {
  return function() {
    document.getElementById(elemId).focus();
  };
};

FFI it.

foreign import data FOCUS :: !

foreign import setFocusImpl :: forall e. Fn1 String (Eff (focus :: FOCUS | e) Unit)

setFocus :: forall e. String -> Eff (focus :: FOCUS | e) Unit
setFocus = runFn1 setFocusImpl

And then use the setFocus function in the initializer.

H.input
[ A.id_ "inputField"
, A.Initializer do
    liftEff $ setFocus "inputField"
    pure DoNothing
] [ ]

Note that I'm using an old version of halogen where the signature is still the old one (definition of Initializer in 30e8b2c7).

Sign up to request clarification or add additional context in comments.

1 Comment

this solution requires assigning ids to nodes which complicates dynamic interface with multiple replicas. Isolation is not preserved.
1

The mothod which is described here is a bit outdated. It is not necessary to write the foreign focus function. It exists already in the Web.HTML.HTMLElement library. I describe the updated method in my blog post here: Focus Input Element

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.