We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I have an input element on the page, and I would like for the cursor to automatically be in the input element when the pages loads. I believe that I need to use the autofocus attribute. Is this correct? Here are some examples of what I have tried:
input.attribute("autofocus");
input.attribute("autofocus", true);
input.attribute("autofocus", "true");
I would appreciate any suggestions you may have. Thanks in advance.
Answers
HTMLInputElement::autofocus attribute only kicks in when the page is loading and if it isn't hidden:
https://Developer.Mozilla.org/en-US/docs/Web/HTML/Element/input#attr-autofocus
However, by the time a p5.js sketch is running, the page loading has already finished. #-o
You're gonna need to manually give focus to it by invoking HTMLElement::focus() method:
https://Developer.Mozilla.org/en-US/docs/Web/API/HTMLElement/focus
And in order to access any underlying native member of a p5.Element, you're gonna need to access property elt 1st: >-)
https://p5js.org/reference/#/p5.Element/elt
Given your p5.Element reference is stored in variable input, in order to invoke its underlying HTMLElement::focus() method, you can do it like this: *-:)
input.elt.focus();
GoToLoop,
Thanks so much for the help.
Glad I could help you! BtW, the shortest
input.attribute('autofocus');
is probably enough to activate the focus effect. A pity it's pretty much useless when it's set inside p5.js. >-)