[JavaScript] Virtual Keyboard
Virtual kayboard/keypad in vanilla JavaScript [1] (plain JavaScript without any additional library/framework like jQuery, Vue.js, or AngularJS).
Real world application is Pāli Dictionary. There are special characters in romanized Pāli. For the convenience of input Pāli words, users can use the virtual keyboard to type Pāli word without installation of Pāli input method in computers
Source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <!doctype html> <html> <head> <meta charset="utf-8"> <title>JavaScript Virtual Keypad Demo</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="keypad.css"> </head> <body> <input type="text" id="userinput"><br> <div class="keypad"></div> <script src="app.js"></script> </body> </html> |
The logic in JavaScript code is simple:
- Create input element for each letter in Pāli alphabet.
- Listen to click event of the input element. In the callback of click event, add the corresponding Pāli letter to the user input.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 'use strict'; function createKeypad() { var word = document.querySelector("#userinput"); var keypad = document.querySelector(".keypad"); const letters = [ ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'], ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'], ['z', 'x', 'c', 'v', 'b', 'n', 'm'], ['ā', 'ḍ', 'ī', 'ḷ', 'ṁ', 'ṃ', 'ñ', 'ṇ', 'ṭ', 'ū', 'ŋ', 'ṅ'] ]; for (var row = 0; row < letters.length; row++) { var divElm = document.createElement("div"); for (var i = 0; i < letters[row].length; i++) { var inputElm = document.createElement("input"); inputElm.type = "button"; inputElm.value = letters[row][i]; divElm.appendChild(inputElm); inputElm.addEventListener("click", function(e) { word.value += e.target.value; }, false); } keypad.appendChild(divElm); } } createKeypad(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 | .keypad { position: absolute; border: 1px solid #ccc; padding: 10px; cursor: move; z-index: 21; text-align: center; background-color: #F0F8FF; } .keypad > div { display: block; } |
Tested on:
- Chromium Version 55.0.2883.87 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)
References:
[1] | javascript - What is VanillaJS? - Stack Overflow |
[3] | [AngularJS] Virtual Keyboard |
[4] | [Vue.js] Virtual Keyboard |
[5] | [Dart] Virtual Keyboard |
[6] | [GopherJS] Virtual Keyboard |