Advertisement
  1. Code
  2. JavaScript
  3. jQuery

Creating a Keyboard With CSS and jQuery

Scroll to top

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 and it could also be a good jQuery virtual keyboard example.

Wondering what a jQuery mobile virtual keyboard looks like? Here's the final preview of the HTML and CSS keyboard key we're going to build:

Now that you know how a jQuery mobile virtual keyboard looks like, let's begin.

1. Create the Basic HTML and Files

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 list item will have a class attached to it, used in both the CSS and jQuery. Most of the classes are just letter, lastitem, or something similar. This will make it easy to find out which list item is which.

Make sure you have set up a folder wherever you are going to be using this keyboard. In 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.

1
my-keyboard-folder/
2
├── index.html
3
├── css/
4
│   └── style.css
5
└── js/
6
    └── keyboard.js

In 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.

1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
  <meta charset="UTF-8">
5
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
  <title>Online Keyboard</title>
8
  <link rel="stylesheet" type="text/css" href="css/style.css" />
9
</head>
10
<body>
11
  <div id="container">
12
    <textarea id="write" rows="6" cols="60"></textarea>
13
    <ul id="keyboard">
14
        <li class="symbol"><span class="off">`</span><span class="on">~</span></li>
15
        <li class="symbol"><span class="off">1</span><span class="on">!</span></li>
16
        <li class="symbol"><span class="off">2</span><span class="on">@</span></li>
17
        <li class="symbol"><span class="off">3</span><span class="on">#</span></li>
18
        <li class="symbol"><span class="off">4</span><span class="on">$</span></li>
19
        <li class="symbol"><span class="off">5</span><span class="on">%</span></li>
20
        <li class="symbol"><span class="off">6</span><span class="on">^</span></li>
21
        <li class="symbol"><span class="off">7</span><span class="on">&amp;</span></li>
22
        <li class="symbol"><span class="off">8</span><span class="on">*</span></li>
23
        <li class="symbol"><span class="off">9</span><span class="on">(</span></li>
24
        <li class="symbol"><span class="off">0</span><span class="on">)</span></li>
25
        <li class="symbol"><span class="off">-</span><span class="on">_</span></li>
26
        <li class="symbol"><span class="off">=</span><span class="on">+</span></li>
27
        <li class="delete lastitem">delete</li>
28
        <li class="tab">tab</li>
29
        <li class="letter">q</li>
30
        <li class="letter">w</li>
31
        <li class="letter">e</li>
32
        <li class="letter">r</li>
33
        <li class="letter">t</li>
34
        <li class="letter">y</li>
35
        <li class="letter">u</li>
36
        <li class="letter">i</li>
37
        <li class="letter">o</li>
38
        <li class="letter">p</li>
39
        <li class="symbol"><span class="off">[</span><span class="on">{</span></li>
40
        <li class="symbol"><span class="off">]</span><span class="on">}</span></li>
41
        <li class="symbol lastitem"><span class="off">\</span><span class="on">|</span></li>
42
        <li class="capslock">caps lock</li>
43
        <li class="letter">a</li>
44
        <li class="letter">s</li>
45
        <li class="letter">d</li>
46
        <li class="letter">f</li>
47
        <li class="letter">g</li>
48
        <li class="letter">h</li>
49
        <li class="letter">j</li>
50
        <li class="letter">k</li>
51
        <li class="letter">l</li>
52
        <li class="symbol"><span class="off">;</span><span class="on">:</span></li>
53
        <li class="symbol"><span class="off">'</span><span class="on">&quot;</span></li>
54
        <li class="return lastitem">return</li>
55
        <li class="left-shift">shift</li>
56
        <li class="letter">z</li>
57
        <li class="letter">x</li>
58
        <li class="letter">c</li>
59
        <li class="letter">v</li>
60
        <li class="letter">b</li>
61
        <li class="letter">n</li>
62
        <li class="letter">m</li>
63
        <li class="symbol"><span class="off">,</span><span class="on">&lt;</span></li>
64
        <li class="symbol"><span class="off">.</span><span class="on">&gt;</span></li>
65
        <li class="symbol"><span class="off">/</span><span class="on">?</span></li>
66
        <li class="right-shift lastitem">shift</li>
67
        <li class="space lastitem">&nbsp;</li>
68
    </ul>
69
</div>
70
  
71
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
72
<script type="text/javascript" src="js/keyboard.js"></script>
73
</body>
74
</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.

HTML SkeletonHTML SkeletonHTML Skeleton
HTML Skeleton

2. Make the List Pretty With CSS

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-explanatory, but there are a couple that I will go over. Save the following CSS in the style.css file located in the css folder.

1
* {
2
margin: 0;
3
padding: 0;
4
}
5
6
body {
7
font: 71%/1.5 Verdana, Sans-Serif;
8
background: #eee;
9
}
10
11
#container {
12
margin: 100px auto;
13
width: 688px;
14
}
15
16
#write {
17
margin: 0 0 5px;
18
padding: 5px;
19
width: 671px;
20
height: 200px;
21
font: 1em/1.5 Verdana, Sans-Serif;
22
background: #fff;
23
border: 1px solid #f9f9f9;
24
border-radius: 5px;
25
}
26
27
#keyboard {
28
margin: 0;
29
padding: 0;
30
list-style: none;
31
}
32
33
    #keyboard li {
34
    float: left;
35
    margin: 0 5px 5px 0;
36
    width: 40px;
37
    height: 40px;
38
    line-height: 40px;
39
    text-align: center;
40
    background: #fff;
41
    border: 1px solid #f9f9f9;
42
    border-radius: 5px;    
43
    }
44
    
45
        .capslock, .tab, .left-shift {
46
        clear: left;
47
        }
48
        
49
            #keyboard .tab, #keyboard .delete {
50
            width: 70px;
51
            }
52
            
53
            #keyboard .capslock {
54
            width: 80px;
55
            }
56
            
57
            #keyboard .return {
58
            width: 77px;
59
            }
60
            
61
            #keyboard .left-shift {
62
            width: 95px;
63
            }
64
            
65
            #keyboard .right-shift {
66
            width: 109px;
67
            }
68
            
69
        .lastitem {
70
        margin-right: 0;
71
        }
72
        
73
        .uppercase {
74
        text-transform: uppercase;
75
        }
76
        
77
        #keyboard .space {
78
        clear: left;
79
        width: 681px;
80
        }
81
        
82
        .on {
83
        display: none;
84
        }
85
        
86
        #keyboard li:hover {
87
        position: relative;
88
        top: 1px;
89
        left: 1px;
90
        border-color: #e5e5e5;
91
        cursor: pointer;
92
        }

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 key in any row will have its right margin zeroed out so the layout won't break.
After stylingAfter stylingAfter styling
After styling

3. Bringing the Keys to Life With JavaScript

If you were to click on a list item now, 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.

1
$(function(){
2
    var $write = $('#write'),
3
		shift = false,
4
		capslock = false;
5
	
6
	// The rest of the code goes here.

7
});

What comes next is attaching the click handler to all the list items (keys). Two variables are set up when the key is clicked. $this is defined just to require 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.

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

4
	
5
	// Code for processing the key.

6
}

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 so as not to do anything else with the character variable.

1
// Shift keys

2
if ($this.hasClass('left-shift') || $this.hasClass('right-shift')) {
3
    $('.letter').toggleClass('uppercase');
4
	$('.symbol span').toggle();
5
	
6
	shift = (shift === true) ? false : true;
7
	capslock = false;
8
	return false;
9
}

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.

1
// Caps lock

2
if ($this.hasClass('capslock')) {
3
    $('.letter').toggleClass('uppercase');
4
	capslock = true;
5
	return false;
6
}

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 so as not to run anything else.

1
// Delete

2
if ($this.hasClass('delete')) {
3
    var html = $write.html();
4
	
5
	$write.html(html.substr(0, html.length - 1));
6
	return false;
7
}
DeleteDeleteDelete
Delete

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 character is (obviously) used for the space bar. The tab character is represented by \t, and finally a new line (the return key) is \n.

1
// Special characters

2
if ($this.hasClass('symbol')) character = $('span:visible', $this).html();
3
if ($this.hasClass('space')) character = ' ';
4
if ($this.hasClass('tab')) character = "\t";
5
if ($this.hasClass('return')) character = "\n";
Special CharactersSpecial CharactersSpecial Characters
Special Characters

Uppercase Letters

If you can remember 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.

1
// Uppercase letter

2
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".

1
// Remove shift once a key is clicked.

2
if (shift === true) {
3
    $('.symbol span').toggle();
4
	if (capslock === false) $('.letter').toggleClass('uppercase');
5
	
6
	shift = false;
7
}
8
9
// Add the character

10
$write.html($write.html() + character);
KeyboardKeyboardKeyboard
The completed keyboard. This is how a completed jQuery on screen keyboard looks. 

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 keyboard powered by CSS and jQuery. You might have also learnt some JavaScript keyboard shortcuts for jQuery. The keyboard isn't totally useless. I've seen websites where 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. Use what we created here as a good jQuery virtual keyboard example.

This post has been updated with contributions from Kingsley Ubah and Janila Castañeda. Kingsley is passionate about creating content that educates and inspires readers. Hobbies include reading, football and cycling. Janila is a staff writer for Envato Tuts+.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.