KeyTyped not working until mouse is pressed

Hello,

I’ve taken the below code from this example:
https://p5js.org/reference/#/p5/keyTyped
and I’m using openprocessing.org as an editor, if that’s helpful in this situation.

In order to be able to get the sketch to respond to a key being pressed, I first have to click on the square. Nothing works until I do that. Does anyone have an idea of why that is?

let color = 180;

function setup() {
	colorMode(HSB);
}

function draw() {
	fill(color, 255, 255);
	rect(25, 25, 50, 50);
}

function keyTyped() {
	if (key === 'q') {
		color = 0;
	} else if (key === 'w') {
		color = 20;
	} else if (key === 'e') {
		color = 40;
	} else if (key === 'r') {
		color = 60;
	} else if (key === 't') {
		color = 80;
	} else if (key === 'y') {
		color = 100;
	}
	return false; // this line prevents any default behaviour
}

Guessing that openprocessing is a browser environment like the Web Editor, which shows similar behaviour. It’s because another part of the browser is selected/focused (might have a specific name, not sure). It’s the same the other way around: after clicking on square and pressing buttons, these characters won’t be added to your text editor hence leaving your code intact.

Does that answer your question?

Yeah, the sketch doesn’t have the focus

Maybe tab works too

In my case, keyTyped() works right after I click at the play :arrow_forward: icon.

Only when I click somewhere else, or return from another browser tab, I’d need to click at the square, or within 25 pixels far from it, to regain focus.

That focus regaining is needed b/c most code webhosters like:

and many others actually run our code inside an <iframe> tag:
Developer.Mozilla.org/en-US/docs/Web/HTML/Element/iframe

And the size of that <iframe> is what actually determines the focus zone for our code.

In the online sketch “Damper Balls” below:

all the balls horizontally follow the mouse as long as the mouse pointer is within the canvas zone, b/c its <iframe> is exactly the same size of that sketch’s <canvas> element.

However, the very same sketch in the alternative link below:
Bl.ocks.org/GoSubRoutine/raw/fa085945d45152786698f44a9523ccac/

all the balls horizontally follow the mouse pointer no matter where it is within the browser’s whole window zone.

That’s b/c this time the running sketch isn’t inside an <iframe> element anymore.

1 Like

Thanks so much everyone for your input; this adds a ton of clarity to the problem :slight_smile:

Does anyone know if there is code that can be added that forces the browser to switch to the canvas as the area of the browser that is active?

A post was split to a new topic: Sound in setup doesn’t play from openprocessing

frameElement && frameElement.focus();