What's Recommend Method For Setting Focus On Elements?

This is the process that I’m using currently, but it does not set the focus on page/modal load.

  1. Add a custom HTML attribute of ID to get something like
    <input type="text" id="txtFirstName" name="something"/>
    in the rendered html
  2. Add a Workflow for On Click for the source element like the field label with custom JavaScript to be this
    document.getElementById("txtFirstName").focus();

Now when you click on the field label, the input has focus.

What is the recommended method to do this?

1 Like

You can add the id to the weweb input element as well. No need for custom html for adding an id.

The problem is that when document.getElementById("txtFirstName").focus(); executes the input element probably does not exist in the dom yet.
Some options are:

  • add a delay before the focus (quick solution but not the best)
  • use MutationObserver to observe when the input is actually in the dom

you can try this:

  • add my-input as id of the modal section
  • add modal-input as id to the input inside the modal
  • in the workflow where you need to focus the input of the modal add a js action with this code:
const observer = new MutationObserver(function (mutationsList, ob) {
	mutationsList.forEach(function (mutation) {
		mutation.addedNodes.forEach(function (addedNode) {
			if (addedNode.tagName) {
				const el = addedNode.querySelector("#modal-input");
				if (el) {
					el.focus();
					ob.disconnect();
				}
			}
		});
	});
});

const el = document.querySelector("#modal-input");
if (el) {
	el.focus();
} else {
	const modal = document.querySelector("#my-modal");
	observer.observe(modal, { subtree: true, childList: true });
}
1 Like