Getting Keyboard Input


Getting Keyboard Input

There are two ways to accept user input from their keyboard:

Displays a window with a text entry box asking the user to enter some text. An example use is getting the player's name for a high-score table.
Used for displaying an on-screen keyboard and receiving key presses.

Due to incompatibilities between Android software keyboards from different vendors and the inability to detect autocomplete text on iOS, we strongly recommend the use of Z.Prompt over Z.Keyboard.


The first step in using Z.Prompt is to create a new Z.Prompt object:

var myprompt = Z.Prompt({
  title: "Hello",
  text: "Please enter your name:",
  defaultValue: "Dog",
  maxLength: 12,
  filterProfanity: true

The various parameters can be used to change the appearance and functionality of the dialog. The filterProfanity option will attempt to replace bad language with punctuation but users with a creative vocabulary may still find ways to be offensive.

The second step is to register event handlers that will be fired when the user has finished entering their text. The confirm event is fired when they tap the "OK" button. The entered text is passed as the single argument to the function.

myprompt.on("confirm", function(theirEntry : string) {
  console.log("They entered: " + theirEntry);

You can optionally also register a function to be fired if the user cancels the text entry dialog:

myprompt.on("cancel", function() {
  console.log("They cancelled the dialog :-(");

After registering event handlers the final step is to display the text entry dialog using the show() function.;

For more information see the Z.Prompt reference page.


A Z.Keyboard object allows you to display the on-screen keyboard and listen for key presses.

This first step is to create a new Z.Keyboard object:

var mykeyboard = Z.Keyboard();

The second step is to register event handlers that will be called when the user presses buttons on the keyboard. The key event is called when the user presses a key. The key they pressed is passed as the sole argument to the function.

mykeyboard.on("key", function(key) {
  if (key === "\n") {
    console.log("They pressed return!");
  } else {
    console.log("They pressed: " + key);

Note that if the return key is pressed then the argument will have the value "\n".

A separate event handler can be registered for listening for the backspace key:

mykeyboard.on("backspace", function() {
  console.log("They pressed backspace!");

Once event handlers have been registered the last step is to show the on-screen keyboard. Note that this step is necessary even on platforms and devices that have a physical keyboard rather than an on-screen keyboard.;

When the keyboard is no longer required it can be hidden using the hide() function:


For more information see the Z.Keyboard reference page.

Open in new window