Martinos Martinos - 5 months ago 55
HTML Question

How to set focus on an element in Elm?

How can I set the focus on a Html element in Elm? I tried to set the autofocus attribute on the element and it only sets the focus on the page load.


A workaround for this is to use Mutation Observers. Insert this JavaScript either in your main HTML page or in the main view of your Elm code:

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
var target = document.querySelector('body > div');
var config = { childList: true, subtree: true };
observer.observe(target, config);

function handleAutofocus(nodeList) {
  for (var i = 0; i < nodeList.length; i++) {
    var node = nodeList[i];
    if (node instanceof Element && node.hasAttribute('data-autofocus')) {
    } else {

Then create HTML elements by including Html.Attributes.attribute "data-autofocus" "".