Creating a Keyboard with CSS and jQuery

Creating a Keyboard with CSS and jQuery

Sometimes it’s just fun to play around with the programming languages we know and see what we can create. I thought it might be nice to create a little online keyboard with CSS, and then make it work with jQuery. The keyboard includes “action” keys (caps lock, shift, and delete) which dynamically changes the keyboard when clicked. I’ll show you how to build it today.


Step 1: Basic HTML and Files

Final Product

This keyboard requires a lot of HTML setup and playing around with CSS. Each of the keys will be represented by a list item in an unordered list. Each of the list items will have a class attached to them, used in both the CSS and jQuery. Most of the classes are just “letter”, “lastitem”, or something similar. This will make finding out which list item is which easy.

Make sure you have setup a folder wherever you are going to be using this keyboard. Inside this new folder, create an index.html file along with a css and a js folder. Finally, create a keyboard.js file in the js folder and a style.css file in the css folder.

Organization of the files

Inside the HTML file we’ll be including two JavaScript files and one CSS file. Inside the body tag there will be a HUGE unordered list containing all the letters, numbers, and some “action” keys. The HTML will also have a textarea in it with an id of “keyboard”. This will be the place where all the characters are added. The below code should be placed inside the index.html file.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

	<title>Online Keyboard</title>
	<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>

<div id="container">
	<textarea id="write" rows="6" cols="60"></textarea>
	<ul id="keyboard">
		<li class="symbol"><span class="off">`</span><span class="on">~</span></li>
		<li class="symbol"><span class="off">1</span><span class="on">!</span></li>
		<li class="symbol"><span class="off">2</span><span class="on">@</span></li>
		<li class="symbol"><span class="off">3</span><span class="on">#</span></li>
		<li class="symbol"><span class="off">4</span><span class="on">$</span></li>
		<li class="symbol"><span class="off">5</span><span class="on">%</span></li>
		<li class="symbol"><span class="off">6</span><span class="on">^</span></li>
		<li class="symbol"><span class="off">7</span><span class="on">&amp;</span></li>
		<li class="symbol"><span class="off">8</span><span class="on">*</span></li>
		<li class="symbol"><span class="off">9</span><span class="on">(</span></li>
		<li class="symbol"><span class="off">0</span><span class="on">)</span></li>
		<li class="symbol"><span class="off">-</span><span class="on">_</span></li>
		<li class="symbol"><span class="off">=</span><span class="on">+</span></li>
		<li class="delete lastitem">delete</li>
		<li class="tab">tab</li>
		<li class="letter">q</li>
		<li class="letter">w</li>
		<li class="letter">e</li>
		<li class="letter">r</li>
		<li class="letter">t</li>
		<li class="letter">y</li>
		<li class="letter">u</li>
		<li class="letter">i</li>
		<li class="letter">o</li>
		<li class="letter">p</li>
		<li class="symbol"><span class="off">[</span><span class="on">{</span></li>
		<li class="symbol"><span class="off">]</span><span class="on">}</span></li>
		<li class="symbol lastitem"><span class="off">\</span><span class="on">|</span></li>
		<li class="capslock">caps lock</li>
		<li class="letter">a</li>
		<li class="letter">s</li>
		<li class="letter">d</li>
		<li class="letter">f</li>
		<li class="letter">g</li>
		<li class="letter">h</li>
		<li class="letter">j</li>
		<li class="letter">k</li>
		<li class="letter">l</li>
		<li class="symbol"><span class="off">;</span><span class="on">:</span></li>
		<li class="symbol"><span class="off">'</span><span class="on">&quot;</span></li>
		<li class="return lastitem">return</li>
		<li class="left-shift">shift</li>
		<li class="letter">z</li>
		<li class="letter">x</li>
		<li class="letter">c</li>
		<li class="letter">v</li>
		<li class="letter">b</li>
		<li class="letter">n</li>
		<li class="letter">m</li>
		<li class="symbol"><span class="off">,</span><span class="on">&lt;</span></li>
		<li class="symbol"><span class="off">.</span><span class="on">&gt;</span></li>
		<li class="symbol"><span class="off">/</span><span class="on">?</span></li>
		<li class="right-shift lastitem">shift</li>
		<li class="space lastitem">&nbsp;</li>
	</ul>
</div>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="js/keyboard.js"></script>
</body>
</html>

You won’t have to worry too much about the classes on the list items for now. I’ll explain them more when we’re using jQuery. However, some of the classes (like right-shift and lastitem) are just there because of the CSS we’ll be using.

The HTML before CSS is applied.

Step 2: Making the List Pretty

The JavaScript for the keyboard would work perfectly fine without any CSS, but it wouldn’t look like a keyboard. I’m not going to explain every style because a lot of them are pretty self-explainitory, but there are a couple that I will go over. Save the following CSS in the style.css file located in the css folder.

* {
margin: 0;
padding: 0;
}
body {
font: 71%/1.5 Verdana, Sans-Serif;
background: #eee;
}
#container {
margin: 100px auto;
width: 688px;
}
#write {
margin: 0 0 5px;
padding: 5px;
width: 671px;
height: 200px;
font: 1em/1.5 Verdana, Sans-Serif;
background: #fff;
border: 1px solid #f9f9f9;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
#keyboard {
margin: 0;
padding: 0;
list-style: none;
}
	#keyboard li {
	float: left;
	margin: 0 5px 5px 0;
	width: 40px;
	height: 40px;
	line-height: 40px;
	text-align: center;
	background: #fff;
	border: 1px solid #f9f9f9;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
	}
		.capslock, .tab, .left-shift {
		clear: left;
		}
			#keyboard .tab, #keyboard .delete {
			width: 70px;
			}
			#keyboard .capslock {
			width: 80px;
			}
			#keyboard .return {
			width: 77px;
			}
			#keyboard .left-shift {
			width: 95px;
			}
			#keyboard .right-shift {
			width: 109px;
			}
		.lastitem {
		margin-right: 0;
		}
		.uppercase {
		text-transform: uppercase;
		}
		#keyboard .space {
		clear: left;
		width: 681px;
		}
		.on {
		display: none;
		}
		#keyboard li:hover {
		position: relative;
		top: 1px;
		left: 1px;
		border-color: #e5e5e5;
		cursor: pointer;
		}

Take notice of the following styles because they are very important.

  • .on – In some of the list items, there are two spans. These are the keys that have more than one character per key; like the numbers. The span with the on class will be hidden. This changed when a user clicks on the shift key, but more on that later with the JavaScript.
  • .lastitem – The last jey in any row will have its right margin zeroed out so the layout won’t break.
Before and after the CSS is applied.

Step 3: Bringing the Keys to Life

If you were to click on a list item nothing would happen. We’re about to fix that with a little jQuery. The main idea we’ll be using is to attach a click handler to each of the list items, grab the text when clicked, and do some magic to it depending on the list item’s class. From here on out, all the JavaScript code will go into the keyboard.js file.

The Setup

We need to open up jQuery and define three variables that will be used through the code. These variables are the textarea, a shift status, and a caps lock status.

$(function(){
	var $write = $('#write'),
		shift = false,
		capslock = false;

	// The rest of the code goes here.
});

What comes next is attaching the click handler to all the list items (keys). Two variables are setup when the key is clicked. $this is defined just to required less typing from us, and character is defined as the HTML of the list item. If the list item is a letter, nothing will happen to this variable, and it will be returned.

$('#keyboard li').click(function(){
	var $this = $(this),
		character = $this.html(); // If it's a lowercase letter, nothing happens to this variable

	// Code for processing the key.
});

The Shift Key and Caps Lock

If the shift key (list items with the class of “left-shift” or “right-shift”) is clicked, we want to toggle the “uppercase” class of each letter. Then for the list items with a class of “symbol,” we want to toggle the display between the nested span tags. What we want to do next is set shift to the opposite boolean value (if it’s true set it to false, and vice versa), and the caps lock variable to false, and finally return false to not do anything else with the character variable.

// Shift keys
if ($this.hasClass('left-shift') || $this.hasClass('right-shift')) {
	$('.letter').toggleClass('uppercase');
	$('.symbol span').toggle();

	shift = (shift === true) ? false : true;
	capslock = false;
	return false;
}

Now, if the caps lock key is clicked, we will toggle the “uppercase” class on letter list items; set the caps lock variable to true; and return false.

// Caps lock
if ($this.hasClass('capslock')) {
	$('.letter').toggleClass('uppercase');
	capslock = true;
	return false;
}

The Delete Key

For the delete key, we need to assign another variable: html – the contents of what’s currently in the textarea. Once we have that, we set the new HTML of the textarea to everything but the last character. This is done with JavaScript’s substr method. Once again we return false as to not run anything else.

// Delete
if ($this.hasClass('delete')) {
	var html = $write.html();

	$write.html(html.substr(0, html.length - 1));
	return false;
}
The markup behind the delete key.

Special Characters

For all the list items which aren’t a letter and aren’t one of the “actions” keys, we change the character variable to something special. For a list item with the “symbol” class, character is set to the contents of whatever span is visible. A space is (obviously) used for the space bar. The tab character is represented by \t, and finally a new line (the return key) is \n.

// Special characters
if ($this.hasClass('symbol')) character = $('span:visible', $this).html();
if ($this.hasClass('space')) character = ' ';
if ($this.hasClass('tab')) character = "\t";
if ($this.hasClass('return')) character = "\n";
The markup behind the symbol keys.

Uppercase Letters

If you can remember to when we handled the shift and caps lock keys, an “uppercase” class was either added or removed using the toggleClass function. If the uppercase class is found, the character is converted to its uppercase form with the help of the toUpperCase method.

// Uppercase letter
if ($this.hasClass('uppercase')) character = character.toUpperCase();

The Aftermath

On a normal keyboard, you usually only need the shift key for one letter. If the shift variable is found to be set to true, we want to toggle the display of the symbol’s spans. What also happens is that if the caps lock key is “on”, the letters are once again toggled between uppercase and lowercase.

To finish off, the character is added to the textarea and the user can continue “typing”.

// Remove shift once a key is clicked.
if (shift === true) {
	$('.symbol span').toggle();
	if (capslock === false) $('.letter').toggleClass('uppercase');

	shift = false;
}

// Add the character
$write.html($write.html() + character);

Final JavaScript Code

$(function(){
	var $write = $('#write'),
		shift = false,
		capslock = false;

	$('#keyboard li').click(function(){
		var $this = $(this),
			character = $this.html(); // If it's a lowercase letter, nothing happens to this variable

		// Shift keys
		if ($this.hasClass('left-shift') || $this.hasClass('right-shift')) {
			$('.letter').toggleClass('uppercase');
			$('.symbol span').toggle();

			shift = (shift === true) ? false : true;
			capslock = false;
			return false;
		}

		// Caps lock
		if ($this.hasClass('capslock')) {
			$('.letter').toggleClass('uppercase');
			capslock = true;
			return false;
		}

		// Delete
		if ($this.hasClass('delete')) {
			var html = $write.html();

			$write.html(html.substr(0, html.length - 1));
			return false;
		}

		// Special characters
		if ($this.hasClass('symbol')) character = $('span:visible', $this).html();
		if ($this.hasClass('space')) character = ' ';
		if ($this.hasClass('tab')) character = "\t";
		if ($this.hasClass('return')) character = "\n";

		// Uppercase letter
		if ($this.hasClass('uppercase')) character = character.toUpperCase();

		// Remove shift once a key is clicked.
		if (shift === true) {
			$('.symbol span').toggle();
			if (capslock === false) $('.letter').toggleClass('uppercase');

			shift = false;
		}

		// Add the character
		$write.html($write.html() + character);
	});
});
Final Product

Conclusion

Sometimes it’s nice to play around, even if the final product isn’t truly “real world.” By applying a few classes to our list items, we were able to create a CSS and jQuery powered keyboard. The keyboard isn’t totally useless. I’ve seen websites were there’s an option for an on-screen keyboard. But mostly, this allows us to gain a better understanding of the capabilities of CSS and jQuery.


Add Comment

Discussion 152 Comments

Comment Page 3 of 3 1 2 3
  1. Lawan says:

    Hi Vasili,

    In Mozilla firefox ver.3.5.11, I find that after I use the real keyboard I can no longer use the virtual keyboard.

    However this problem dosent occur on IE 8. I have looked at the jquery and everything seems fine.

    Have you found a fix for this. Apart from that this keyboard is gr8. :)

  2. mklaman says:

    i too would like to see this work with multiple inputs and not just one textarea. any one have ideas?

  3. mhamed says:

    I ve done a lot of searches to find an easy way to develop virtual keaboard in to write in Arabic
    I found this tutorial as good help
    downloaded the demo worked it out and the result is something like this on the wordtosay.com

  4. fcsonline says:

    wow! awesome!

    You can improve de project creating a JQuery plugin, to attach de keyboard to a $(selector).

    Another improvement could be, the integration with jquery.hotkeys to fire special keys, like ESC, F1, F2, CTRL+D, etc… It is interesting for remote web consoles.

    If you need help, I’m here.

    thanks!

  5. Sofia says:

    Thansk Nice Post

  6. Ankit Mahato says:

    there is a bug i found which needs little patching ..
    when u write something in the text area and cut it and paste somewhere like notepad,wordpad,etc ..
    then when u resume the virtual keyboard .. it doesn’t work.

    i am working on it and just about to fix it .. will post very soon ..

  7. John Murray says:

    I’m building a Kiosk application for the local transit authority and this is absolutely perfect. This is exactly what I was looking for. Thanks for the great tutorial!

  8. Pablo says:

    A great post!!! congratulations!

  9. Jordi says:

    This is a really nice Keyb, unfortunately I can’t use use it because I’m not able of changing succesfully the textarea into an input box. Could you let me know how-to do it?
    Thanks so much in advance.
    Cheers.

  10. This was a great tutorial! I love how this worked out, thank you!

  11. Frank says:

    Thanks needed a base to work on for an onscreen keyboard. Saves me quite some time ^_^

  12. Asif says:

    this is great tutorial, but one bug is still there, it does not work on input type text. it is just working fine on textarea, can any one help me out how it will work in input text???

  13. illemeInfumma says:

    hi nice post we have going there!

  14. illemeInfumma says:

    hi nice post we have going here.

  15. illemeInfumma says:

    Just read the thread! great job.

  16. illemeInfumma says:

    Hi great post we have going here!

  17. roXon says:

    I found a fast small workaround (bug – using keyboard, than switching back to mouse clicks)

    $write.click(function(){
    $(this).blur();
    });

    But it just makes textarea unavailable to set keyboard ‘focus’ on textarea. Play around and you’ll find a way to fix that too.

  18. shams says:

    I dare somebody to make one without the javascript.

    one dtd
    one css file
    one xslt
    and one xml

    it can be done. I saw it back when xml was just a baby.

  19. Ian says:

    How can I set the caps as ON for default?

  20. JeremyMn says:

    XRumer 5 free does not work , where to download Xrumer 7.0 Elite?
    write a private message or ICQ 98884846

  21. Vinod says:

    Thanks for the code and demo, That looks awesome and i created my own keyboard and linked the js that works great. Only issue is i have multiple input’s instead of textarea, can you tell me how to place this keyboard for the each input and on outblur it shoudl disapear now i have inline js for the input onfocus shwo and on bur hide the keyboard.

    thanks for the help.
    Vinod

  22. cameron says:

    Thanks a mill, really cool :)

  23. godie says:

    wow, i just wanna the numeric jaja, but this tutorial its amazing :)

  24. clay says:

    I noticed a few people are asking for a way to make this work with a form with multiple inputs. I too was wondering the same thing, looking for a keyboard to use with a touchscreen input system for tracking customers, only problem is the customers keep closing the on screen keyboard that is embedded in Win 7 and I need to be able to insert a keyboard such as this to keep them from minimizing or closing the built in keyboard. Any help is appreciated! Nice work, but you don’t give yourself enough credit for the usefulness of this great keyboard!

  25. Pat says:

    Im glad I found this tutorial! I’m trying to figure out how I can use this with a regular input instead of a text area, is it possible? Thanks.

  26. tamiltab says:

    very helpeful information
    thanks !!

  27. Patrick says:

    In case anyone was wondering, I figured out how to change it to use an input field instead of a textarea.

    first of all replace:

    with this:

    Then for the JQuery Replace all instances of
    $write.html
    with:
    $write.val

  28. Sergey says:

    Thank you! I very need it now!

    I already have one onscreen key board, but in clean js and it’s hard.
    This tutorial is very cool!

    Result is clean, beautiful and awesome!

  29. kim says:

    hey great tutorial :D,

    i am trying to enter the letters pressed by the user in the text field selected by the user can it be done? if yes can someone point me in the right direction what to do ?

  30. Sarah says:

    Wanted to use this keyboard for the Arabic lang. It works great except having problems including the English transliteration in Internet Explorer…

    Take a look here: http://arabiccomplete.com/keyboard/index.htm

    Any ideas on how to not have the English transliteration type into the field!

    Thanks –

Comment Page 3 of 3 1 2 3

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.