Wednesday, April 7, 2010

JavaScript Virtual Keyboard

http://www.codeproject.com/KB/scripting/jvk.aspx
Download src jvk

Virtual keyboard bound to a TEXTAREA field

Introduction

Imagine that you are sitting in a London Internet cafe wishing to write an e-mail to your family living in Athens. It's good if someone in your family speaks English. If not, where would you find a keyboard with a Greek layout? I'm sure you can recall a dozen situations when you thought, "I wish I had another keyboard." This article presents the Virtual Keyboard that solves this usability problem. The design task for it can be specified as follows:

  • Allow text input from computers without the user's native language layout installed, therefore allowing the creation of national and multilingual interfaces -- e.g. Web-based e-mail -- that can be used worldwide.
  • Allow text input from computers without keyboards or with sensor screens -- hand-held PCs, smartphones, etc. -- or with remote controls such as mice, e-pens, etc. being the only input devices.
  • Protect users from keylogger-type spyware.

Installation of the Virtual Keyboard requires a casual knowledge of HTML and JavaScript. To be able to fine-tune the script, you must be familiar with W3C DOM Level 1, CSS Level 1 and the DOM/Microsoft Internet Explorer event model. Virtual Keyboard is an open-source script distributed under the zlib/libpng license.

Setup

Six easy steps:

  1. Download the source archive.

  2. Choose your installation:

    • vkboard.js (1-vkboard folder in the archive) is the primary script. Full keyboard is simulated as follows:

      Screenshot - jvk-full.jpg

    • vkboards.js (2-vkboard_slim folder) is almost the same as previous, but the language menu, which can be accessed by clicking on the red rectangle in the left-bottom corner of the keyboard, has a special configuration. The cells are arranged in rows, not as a simple drop-down menu like in the previous variant.

      Screenshot - jvk-slim.jpg

      This installation is recommended if you're short on space (UMPC, touchscreen kiosk, etc.) or if you have 4 or more layouts installed.

    • vnumpad.js (3-numpad_full folder) is the numpad part of the keyboard.

      numpad variant

    • vatmpad.js (4-numpad_atm folder) is a stripped numpad that contains only the Enter and number keys.

      numpad_atm variant

  3. Include a reference to the chosen script file in your HTML page:

    Collapse
    <HTML>     <HEAD>         <SCRIPT type="text/javascript" src="vkboard.js">SCRIPT>         ...      </HEAD>  ...

    Note that for each type of installation, two script files are available:

    • vkboard.js /vkboards.js /vnumpad.js /vatmpad.js are the original script. If you wish to change the script or just want to learn how it works, this is the file for you to look at.
    • vkboardc.js /vkboardsc.js /vnumpadc.js /vatmpadc.js is a compressed version of the script, respectively 30.5%/30.5%/39.8%/39.5% smaller than the original. This is the file you should use on the Web.
  4. Define a callback function:

    Collapse
    <HTML>     <HEAD>          <SCRIPT type="text/javascript" src="vkboard.js">SCRIPT>          <SCRIPT>          // Minimal callback function:         function keyb_callback(char)         {             // Let's bind vkeyboard to the       ...  

    Note that the up and down arrows on a virtual keyboard work only on standards-compliant browsers! Take this into account when creating touch screen applications. You can test the above script by running the 2-edit-full.html file found in the vkboard folder of the attached archive. Basic callback is demonstrated in 1-edit-simple.html.

    Tips and Tricks

    Script flow is quite straightforward, so I hope it won't be hard to dive into it. Here are a couple of words on a few tricky places.

    • Event set-up. We need to handle both Microsoft Internet Explorer and W3C DOM event models:

      Collapse
      _setup_event: function(elem, eventType, handler) {     return (elem.attachEvent ? // Microsoft Internet Explorer way          elem.attachEvent("on" + eventType, handler) :         ((elem.addEventListener) ? // W3C way          elem.addEventListener(eventType, handler, false) : null)); }
    • Key container set-up. Each key consists of the "outer" DIV -- where we set the top, left, width and height parameters only -- and the "inner" DIV, which accepts padding, border color and other parameters. We use such a complex construction to circumvent the box model problem of modern browsers. Note that there is the JavaScript solution. If you wish to avoid the box model problem using CSS, you may wish to see the article by Trenton Moss (see item #6).

      Collapse
      _setup_key: function(parent, id, top, left, width, height,     text_align, line_height, font_size,     font_weight, padding_left, padding_right) {     var exists = document.getElementById(id);      // Outer DIV:      var key =         exists ? exists.parentNode : document.createElement("DIV");     this._setup_style(key,         !exists, top, left, width, height, "absolute");      // Inner DIV:      var key_sub = exists ? exists : document.createElement("DIV");     key.appendChild(key_sub); parent.appendChild(key);      this._setup_style(key_sub,         !exists, "", "", "", line_height, "relative",         text_align, line_height, font_size, font_weight,         padding_left, padding_right);         key_sub.id = id;      return key_sub; }
    • Disabling content selection. This one is very important due to the very high typing speed that some people can achieve and, as a result, the inevitable vkeyboard content selection. It can be used instead of the UNSELECTABLE (Microsoft Internet Explorer) and -moz-user-select (Gecko-based browsers) properties.

      Collapse
      this._setup_event(kb_main, "selectstart",     function(event)     {         return false;     }); this._setup_event(kb_main, "mousedown",     function(event)     {         if(event.preventDefault)             event.preventDefault();         return false;     }); 

    Code

    Virtual Keyboard Features at a Glance

    • A complete JavaScript toolkit suitable for simulating every single aspect of a real keyboard device
    • Compact (42.8 KB - compressed full variant) script that doesn't require any images, for faster download
    • Works and looks the same way on all mainstream browsers, tested on Mozilla Firefox 1.5/2, Opera 7.5/9.22, Safari 3, Microsoft Internet Explorer 6/7
    • Very simple set-up procedure
    • Self-contained, with no external dependencies
    • Customizable font, font size and colors; perfect for skinable environments
    • Several variants are available, including full keyboard, slim full keyboard, numpad and ATM-style numpad
    • Compressed scripts are bundled, i.e. full script: 42.8 KB, slim: 43 KB, numpad: 9.30 KB, atm-numpad: 8.62 KB
    • Ten frequently used keyboard layouts are bundled with the full and slim scripts, 24 more layouts are in the provided layout pack
    • Flexible installation options, i.e. any number of vkeyboards per page, adjustable callbacks
    • Open-source script distributed under the zlib/libpng license, meaning that it can be used free of charge even on commercial sites

    Script Requirements

    Any browser that is aware of:

    • JavaScript (implementation compliant with ECMAScript Edition 3)
    • W3C DOM Level 1
    • CSS Level 1 (at least, most of the elements)
    • W3C or Microsoft Internet Explorer event model

    Links

    History

    • April 10th, 2006
      • First version, English layout only
    • April 14th, 2006
      • Code refined
      • Russian, German, French, and Czech layouts added
    • April 22nd, 2006
      • Second code revision, much more compact and robust code
      • Spanish, Italian, and Greek layouts added
    • May 14th, 2006
      • Third code revision, even more robust and error-proof code
      • Canadian (multilingual standard) and Hebrew layouts added
      • "AltGr" key and appropriate layout variants added
      • German, French, Spanish, and Greek layouts fixed
      • "Caps Lock" + "Shift" case switching fixed
      • Language menu positioning issue fixed
      • Moved from manual to on-focus switching in the "test2" example
    • May 16th, 2006
      • All "box model"-related issues solved
    • June 12th, 2006
      • Most layouts revised and fixed
      • Minor language menu issue fixed
      • Pilot implementation of the dead keys subsystem
    • August 28th, 2006
      • Keyboard now pops over the page rather than embedding into it
      • Keyboard font size can now be specified, keyboard scales uniformly with font size
      • Keyboard colors can now be customized
      • Shift and AltGr keys now deactivate after alphanumeric key has been pressed
      • Fixed an obscure language menu bug sometimes occurring in Microsoft Internet Explorer
      • Compressed version of script is now bundled in the archive
      • Minor code changes and cleanups, too numerous to be listed
    • September 14th, 2006
    • October 4th, 2006
      • Numpad-only -- 2 variants -- scripts are now bundled in the archive
      • [full keyboard] Fixed problem with an improper cursor positioning when used with Hebrew in edit_simple sample
      • [full keyboard] Many corrections to Greek layout; letters with acute, umlaut and Dialytika Tonos accents are now available
      • [full keyboard] Added optional switch to ShowVKeyboard, that allows you not to create the numpad
    • October 16th, 2006
      • [full keyboard] Dead-keys subsystem reworked
      • [all variants] Slightly more compact and clean code
    • October 26th, 2006
      • Popup-tuned variant of the vkeyboard created
      • [all variants] Key parts of the script were rewritten, resulting in smaller and faster code
      • [all variants] Fixed the annoying issue with key text selection when "typing" fast, due to eventual drag 'n' drop
      • [all variants] Got rid of all browser detection code
      • [full keyboard] Advanced callback function was rewritten; works OK with Microsoft Internet Explorer 6, Firefox 1.5, Opera 9 and Netscape 8.1
    • November 16th, 2006
      • [full keyboard] "test_fly_anonym" sample added
      • [full/popup keyboard] 'new shekel' symbol added to the Hebrew layout
      • [full/popup keyboard] Language names in the language menu were rewritten in the languages they represent
    • December 22nd, 2006
      • [full/popup keyboard] Fixed an issue with the transparent background of the language drop-down menu
      • [full/popup keyboard] Fixed an issue with the language menu not receiving the same font color as the rest of the keyboard
      • [full/popup keyboard] Fixed an issue with the Russian language designator sometimes shown with odd characters
      • [numpad/ATM-numpad] Optimizations and code size reductions
      • [all variants] "Background color" separated into "keyboard base color" and "keys' background color"
      • [all variants] Keyboard font can now be specified
      • [all variants] Further preparations to the next milestone release
    • January 12th, 2007
      • *** Version 2 - interface is incompatible with previous releases ***
      • [all variants] Code refactored and rewritten in an object-oriented fashion, new API, no global variables exposed
      • [all variants] Massive code optimizations, especially in _refresh_layout and _construct (former ShowVKeyboard) methods
      • [all variants] Usage of the eval function was reduced to the absolute minimum: 6 calls in the beginning of _refresh_layout
      • [all variants] Callback function and all visual parameters now can be adjusted at run-time
      • [all variants] Callback function is now stored by reference, not by name
      • [all variants] Callback function now can accept a second parameter
      • [all variants] As a result of refactoring, script now runs up to 30% faster
      • [all variants] Font size can now be specified with any absolute or relative CSS length unit (experimental plug-in; see note)
      • [all variants] Fixed bug when script calculated erroneous padding when changing font size
      • [all variants] Resolved issue with Microsoft Internet Explorer /Mozilla font scaling
      • [full/popup keyboard] Numpad can now be shown/hidden at run-time
      • [full/popup keyboard] Fixed issues with "Enter" key misalignment and glitches
      • [full/popup keyboard] Fixed bug with numpad keys' misalignment when changing font size
      • [full/popup keyboard] Fixed bug when AltGr didn't shadow when Shift was pressed and _alt_gr_shift array was not defined
      • [full keyboard] test_any_css , test_change and test_scale samples added
      • [full keyboard] All samples renamed to form a more consistent test suite
      • [full keyboard] More comments written in all sample installations
      • [popup keyboard] Popup variant is no longer bound to 2 rows per 5 languages each - adaptive configuration
      • changelog.txt (version history) and how-to-compress.txt (obfuscation procedure) files are now shipped with the archive
    • February 6th, 2007
      • [full/popup keyboard] Fixed bug with dead_color parameter not affecting dead keys' color
      • [full/popup keyboard] Breve, DotAbove, DoubleAcute, Macron, and Ogonek diacritic arrays added
      • [full/popup keyboard] Acute, Grave, and Tilde diacritic arrays corrected
      • [ATM-numpad] Fixed erroneous sample
      • [all variants] Better advanced callback function:
        • Fixed bug with improper deletion of multiple characters at once (Mozilla, Opera, Netscape, Microsoft Internet Explorer)
        • Fixed bug with improper character replacements (Microsoft Internet Explorer)
        • Plays better with INPUT fields of type="text"
    • February 14th, 2007
      • *** Version 2.2 - interface is incompatible with previous releases ***
      • [full keyboard] First release of the layout pack; see list
      • [full keyboard] Fixed bugs in advanced callback function that were introduced in the previous release
      • [full keyboard] Macron diacritic array moved to a separate file
      • [full/popup keyboard] New parameter added - background color for the inactive keys
      • [full/popup keyboard] Built-in Czech layout now matches one in IBM layout database, older variant moved to the layout pack
      • [full/popup keyboard] Built-in Hebrew layout now matches one in IBM layout database for normal/casp/shift parts
    • March 26th, 2007:
      • [all variants] Major code cleanup (no evals now!), much cleaner and, generally, faster code
      • [all variants] "keys" can now flash on click, flash colors are customizable
      • [all variants] Virtual keyboard can now either embed into the page or float over the content
      • [all variants] More parameters added (5 to constructor, 4 to SetParameters method) to control the above two features
      • [all variants] Fixed some key text selection issues
      • [full keyboard] Advanced callback function is now (almost) perfect
      • [full/popup keyboard] Reserved keys fired symbol when pressed, fixed
      • [layout pack] Arabic (470) layout added
      • [layout pack] All layout files reformatted to be more readable
    • July 12th, 2007:
      • [full keyboard] Translator script added, scripts starting from 4th renamed to encompass this new test case
      • [full keyboard] 3rd input field in '5-test-fly' and '6-test-fly-anonym' was replaced by a TEXTAREA
      • [full keyboard] Advanced callback function fixed once again (we'll get it right eventually...)
      • [popup keyboard] "popup" variant renamed to "slim", popup sample was dropped due to its poor usability
      • [full/slim keyboard] You can now specify the index of the start-up layout
      • [full/slim keyboard] You can change the layout programmatically with SetParameters function
      • [all variants] You can now specify if there will be a 1-pixel gap between the keys
      • [all variants] Advanced callback function is now the base for all test cases
      • [all variants] Most test cases now make use of backfocus function to address the 'lost focus' annoyance
      • [all variants] Obfuscation procedure was significantly simplified
      • [all variants] Fixed the use of static kbArray variable (doesn't affect you if you're using 1 vkeyboard per page)
    • July 18th, 2007
      • [all variants] Minor optimizations
      • [layout pack] Dutch, Icelandic and Portuguese layouts added
    • July 24th, 2007
      • *** Version 2.6 - interface is incompatible with previous releases ***
      • [full/slim keyboard] Arrow keys can now be shown on vkeyboard creation
      • [full/slim keyboard] Advanced callback function modified to accommodate arrow keys
      • [all variants] Obfuscation procedure was simplified even more
    • March 26th, 2008
      • [full/slim keyboard] Fixed bug with vkeyboard collapse when using arrow keys and the numpad
      • [all variants] Fixed issue with eventual missing of clicks (= VKeyboard is now perfectly usable by touch-screen users)
      • [all variants] Cleared the copyright issue with a DocumentSelection library by Ilya Lebedev
      • [all variants] Obfuscation procedure was simplified once again

    License

    This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    About the Author

    Dmitry Khudorozhkov


    Member
    Dmitry Khudorozhkov began programming (and gaming) with his ZX Spectrum in 1989. Having seen and used all IBM PCs from early XT to the latest x64 machines, now Dmitry is a freelance programmer, 27 years old, living in Moscow, Russia. He is a graduate of the Moscow State Institute of Electronics and Mathematics (Applied Mathematics).

    He is proficient in:

    - C/C++ - more that 9 years of experience. Pure Win32 API/MFC desktop programming, networking (BSD/Win sockets), databases (primarily SQLite), OpenGL;

    - JavaScript - more that 6 years of experience. Client-side components, AJAX, jQuery installation and customization;

    - Firefox extensions (immediatelly ready for addons.mozilla.org reviewing) and Greasemonkey scripts. As an example of extensions Dmitry made you can search for FoxyPrices or WhatBird Winged Toolbar;

    - XML and it's applications (last 2 years): XSLT (+ XPath), XSD, SVG, VML;

    - ASP.NET/C# (webservices mostly);

    Also familiar with (= entry level):

    - PHP;

    - HTML/CSS slicing.

    Trying to learn:

    - Ruby/Ruby-on-Rails;

    - Czech language.

    If you wish to express your opinion, ask a question or report a bug, feel free to e-mail:dmitrykhudorozhkov@yahoo.com. Job offers are warmly welcome.

    If you wish to donate - and, by doing so, support further development - you can send Dmitry a bonus through the Rentacoder.com service (registration is free, Paypal is supported). Russian users can donate to the Yandex.Money account 41001132298694.

    -
    Occupation:Software Developer
    Company:Freelance software engineer
    Location:Russian Federation Russian Federation

1 comment:

Ella Eva said...

Sharkoon RGB Flow Gaming Case in UAE, ATX Gaming Case in UAE, Gaming Case in UAE
https://gccgamers.com/sharkoon-rgb-flow.html
Sharkoon Flow Case in UAE, Safe Shopping Multiple Payment Options Express Delivery GCC Gamers Moneyback Guarantee.
1632379812120-9