Focus an Input

by stephanhoyer

Level: beginner • Mithril.js Version: latest

This example shows how to focus an input element on load right away. It is doing so by using Mithril.js' oncreate lifecycle method, that is called after a DOM element is created and attached to the document.

Live Example


Type Name URL


m.mount(document.body, {
  view: () => [
    m('input[autofocus]', {
      oncreate: ({dom}) => setTimeout(() => dom.focus())
    m('p', 'Click the refresh button in Flems to see the effect')

The snippet is using the most current version of Mithril.js framework. It is aimed at beginners and shows some basic recipes.

In addition to the Mithril.js hyperscript function m(), here we can see an example of Mithril.js' m.mount API method. It also shows, how Mithril.js' lifecycle methods can be used. This can be seen here by using the oncreate hook.

The example was contributed by stephanhoyer and last modified on 22 October 2021. Click here to see more examples contributed by the author.


If anyone has some improvements, that should be addressed, let me know by opening an issue. Or simply fork the repository on GitHub, push your commits and send a pull request. For starting your work, you can click the edit link below. Thanks for contributing.

See more code examples  •  Edit this example on GitHub