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.


Tags: CSSjQuery
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.dsaportfolio.com.br/ Diego SA

    Interesting thing to use. Really well done. I’d only fix the Shift button problem. When you click on Shift button and then click on a letter or number button, they return to what they were before. I’d keep the buttons changed while the user doesn’t click on Shift button again. Except for that, everything is awesome! Congratulations!

    • http://vasili.duove.com/ Vasili

      The only reason I’ve chosen to change them back is because most times, I’ll only need the shift key for one letter/symbol. :)

  • http://myfacefriends.com Myfacefriends

    another unique tuts! thanks!

  • http://URL(Optional) capzspace
  • http://www.tubeget.info vamsi

    Yo !!
    Its Cool …will be using it in one of my sites !

  • abs

    LOL that’s brilliant and well cool

  • Wim

    Perhaps you could combine it with ‘retype’?

    http://myyn.org/retype/jquery-retype/example/

    This combined functionality makes a whole lot of sense to me, special keyboard mappings which are actually visible as you type.

    My 2cw

  • http://www.refinelighting.com ben chen

    i think this is very good

  • http://www.nitroxt.com Tim

    very unique tutorial. thanks

  • http://URL(Optional) megidon75mdn
  • http://1171sms.ru знакомство

    хотела бы с вами поообщаться поближе, снедать ровня вопросов по оформлению и обмену блогами, дозволено вообще поработать

  • http://www.redesignyourbiz.com/ Web Design Mumbai

    this is simply mind blowing… great tut.

  • http://www.AlchemyUnited.com Mark @ AlchemyUnited.com

    @Gaurav Chandra – Yeah, I was thinking the same thing, expect I wouldn’t just limit it to banking sites. Why not use it all the time? Keystroke tracking spyware would have some catching up to do then, eh?

  • http://www.themeheven.com themeheven

    Nice contents really cool

  • http://drimr.com John

    There is a problem if you use both real keyboard and visual keyboard. Btw thanks for your nice tuts

  • http://www.qrafika.az KoLGe

    Thanks a lot. Great!

  • Arefin

    Thanks a lot and Thanks in advance for some nice contents !

  • http://jcargoo.org jcargoo

    Hi,
    There are some missing things like: keyboard arrows, tab button not working behind a typed word, return button is not working as designed (middle of w word, after typing a word) and so other small details. This can be taken into account by other people who want to improve the features. Otherwise it is a great work.
    Thanks.

  • Thany

    Next steps:

    - Make it possible to repeat keys by holding them down (especially useful for the delete/backspace keys)
    - Allow input of nonwestern characters, most notably asian languages that combine simplified characters into complex ones.

    Second one may be a little hard tho :)

  • http://new2down.com jawanda

    good work but not works when someone deletes the text with backspace and again tries to write the text from keyboard nothing happens

  • http://tskdesigners.com Salman Khimani

    what if i have multiple input fields to be filled with this keyboard?

    I added below mentioned code after … to work with other input fields but it doesn’t work with other fields :

    can u help me with this please?

  • http://www.dev-hq.co.uk Joe

    Some Issues. But all in all pretty good tut :P

  • cos mashang

    sweet Tut!
    just one question if i wanted to use this to write to multiple fields , how would i go about doing that?

  • http://dremi.info dr.emi

    wow!!! very large code :)

    it’s help me.

  • vinic

    Great!
    Hi~i come from Beijing~~

  • Fiseha

    Love it, very nice and useful for non English keyboard too.

  • http://www.seoanaliz.net Seo analiz

    thanks… very nice.

  • Dratutsmits

    Confirmo. Y con esto me he encontrado. Discutiremos esta pregunta. http://nuevascarreras.com/ cialis 20 mg efectos Avete visitato una splendida idea cialis o viagra

  • http://iforexvideo.com fore_xstra_tegy

    I am definitely bookmarking this page and sharing it with my friends.

    :)

  • Kir

    In ie (6,7) with each letter the extraneous blank is added. Why?

  • Nader

    Thanks so much, this is brilliant ..

    keep up your excellent work

  • jrodas

    sorry, but i’ve noticed something, when i type with the mouse, there is one space bethween every letter, i’m trying to find out from the file “keyboard.js” but i didn’t find the correct line. i need the letters without any space bethween each other.

    if someone knows how to do it woks, i’ll be so gratefull.

    thanks for the tutorial. (y)

    • Joelson

      Go to the Css File

  • http://www.lab4games.net/zz85/blog/ Joshua Koo

    thanks for the lovely tutorial.

    i’ve improvised on this idea to create a keyboard bookmarklet with html 5 canvas.

    http://www.lab4games.net/zz85/blog/2010/02/06/online-virtual-keyboard-with-canvas-and-javascript/

    • http://www.themindofq.com Q

      Using it for a touch screen interface now at work. It works great.

  • Nik

    I have one problem If a user was to high light the text and delete it which they are more than likely to do you can’t carry on writing.
    Other than that the style is brilliant wounder what it resembles and the click effect is great good job on this.

  • http://www.gsm4bd.com Jhumon

    Really its nice.but I have a problem,I wanna make this keyboard in another language so what should I do ?

  • Thomas

    Hi,
    I was searching for a virtual keyboard to use with a touchscreen and I found this tutorial which apparently looks awesome. But the demo, source and images are missing… Can you do something please ?
    Thank you very much in advance…

  • http://www.ameodia.com Rashmirekha

    The example was a very good one. It behaves abruptly while using Mozilla Firefox. Mine is Version 3.6.3. In Firefox after typing line 11 it did not manage to show me line 12. Can not it be prepared in such a fashion that it will always show the last line so that one can know where the cursor is and type accordingly.

  • ccorp

    Is possible to change this keyborad to input information in another type of textbox ?

    Ex.

    Regards

  • ccorp

    The sample code:

    http://pastebin.com/PxMm2Ee9

    Sorry for dual post

    Regards

  • http://www.quintema.co.uk/ Rosie

    this is good. thanks for the share
    ___________________________________
    get your website optimized at Quintema

  • Xforexer

    Excuse me. Does someone know how to find an actual Forex Expert Avisor from fake and a real trading signals from fraudulent? big thanks

  • http://www.mehmetkabatas.com Chris

    thankS very nice..

  • http://www.sejur-extern.ro Sethh

    Thanks!!!!!!!!!!!!!!!!

    Very nice work!!!!!

    tks again!!!!!

  • http://www.isexpert.eu Dragos

    Hi,

    How can i use this keyboard for 3 inputs?
    Can you help me please?

    I try to change the text area…but nothing…i try tu change the id…

    Can you hel please?

    Thank you in advance!

  • http://newsever.com Newsever

    That’s Really Works!! ,Thanks.

  • Jan

    After using the real key board you can’t use this virtual keyboard any more =(

    How to solve this?

  • jan

    also in the css file
    line 56:
    #keyboard .rightright-shift {

    should be:
    #keyboard .right-shift {

  • jan

    oh and is there someone who knows if it’s possible to show the typing cursor(as normal) and let the text stop flash when you add and character?

  • Me Again

    Well done!!

    Small problem: How do I change de js-file, so it can work with two teaxt areas?
    The textarea that gets the focus gets also id=”write”, the other ta gets id=”nowirite’.

    This doesn(t work in your demo?!

  • http://www.jakenoblewebs.co.uk Jake

    Hi.
    Nice plugin!

    The demo needs to be better though, effecting the body CSS is no good, I am really struggling to implement this without breaking my site!

  • Tass

    Hi

    Great work thank you! Probably a stupid question but how do you get to display what you’ve entered in the keyboard in another place on your website?
    Thanks