How can I programatically set 'focus' in an DOM element with p5.js

I know very little HTML, and just start looking into p5.js (great stuf!!).

For instance, this code from examples in p5.js site:

var input, button, greeting;

function setup() {

  // create canvas
  createCanvas(710, 400);

  input = createInput();
  input.position(20, 65);

  button = createButton('submit');
  button.position(150, 65);

  greeting = createElement('h2', 'what is your name?');
  greeting.position(20, 5);


function greet() {
  var name = input.value();
  greeting.html('hello '+name+'!');

  for (var i=0; i<200; i++) {
    fill(random(255), 255, 255);
    translate(random(width), random(height));
    text(name, 0, 0);

How could I, programatically, lets say with a key or whatever, set the focus to the input created.



  • Answer ✓

    Remember that p5js is JavaScript based; so pretty much any JavaScript code will work in a P5 sketch; you just have to know how to apply it. In the case of forms there's already a JavaScript function to apply focus to an input. Not surprisingly it's called focus(). You'll see from this reference that it has to be applied to a DOM element.

    You've already created the input field programmatically; so you already have a reference to it: the input variable. You then need to get at the DOM element this refers to so you can call the focus() function on it. That's what the elt property does. So the following will do the trick:


  • Thanks @blindfish ! I was missing the elt.

  • Actually, double thanks cause now o got the logic of referencing a DOM element !!


Sign In or Register to comment.