Sunday, July 18, 2010

Google Virtual Keyboard with layout selector using a drop-down menu

Google Web Elements allow you to easily add your favorite Google products onto your own website. I will talk about the Google Virtual Keyboard.
As you can see on its presentation page, Google has implemented a virtual keyboard that lets you type directly in your local language script in an easy and consistent manner. Google's virtual keyboard allows developers to enable virtual keyboards on any text field or text area in their webpages.
How to attach a Virtual Keyboard to inputs on your site
As explained here and here, the steps are:

  1. determine the language(layout) for the keyboard
  2. determine the ids of the input elements where the keyboard will be active
  3. put some javascript code in the html source of the webpage
I needed to be able to select when browser the layout. I found an example here that allows to switch the layout to some predetermined layouts, but this wasn't enought.
After some google I found an example that gets all the available layouts and makes a button(anchor) for each one, so when clicked the layout of the keyboard is changed. 
I prefer using a drop-down menu so the code is:


// Load the Google Onscreen Keyboard API
google.load("elements", "1", {packages: "keyboard"});

var kbd; // A Keyboard object.

// Draw a list of keyboard layouts in their native languages.
// User can click any of them to switch to that keyboard layout.
function drawMenu() {
 html = ["<select onchange='kbd.setLayout(this.options[this.selectedIndex].value)' >"];
 html.push("<option value=\"en\" >", "Select a layout for the virtual keyboard", "</option>");
 for (var i in google.elements.keyboard.LayoutCode) {
  var code = google.elements.keyboard.LayoutCode[i];
  var name = google.elements.keyboard.getLayoutName(code);
  html.push("<option value=\"", code, "\" >", name, "</option>");
 }
   html.push("</select>");
 document.getElementById("kbSelect").innerHTML += html.join("");
}


function onLoad() {
 // Create an instance on Keyboard.
 kbd = new google.elements.keyboard.Keyboard([
  google.elements.keyboard.LayoutCode.ENGLISH],
  ["id1","id2","id3"]);
 drawMenu();
 kbd.setLayout("en");//default language
}

google.setOnLoadCallback(onLoad);


The code works very good so I implemented it in my website design toolkit in a PHP class called PVirtualKeyboard(source code here).

No comments:

Post a Comment