Make an Animated Alphabet using Keypress Events in jQuery

The result here was the result of some random jQuery keypress event experiments over the past few days. I recommend that you use this tutorial as a proof of concept rather than final product.
Let’s be real for a moment — there are very few places where you would need the exact effect we’ll be building. However, the logic behind it should be a much more useful in adapting to your own needs.
The Goal
By the end of this tutorial we’ll have 26 individual letter blocks which will each react to a corresponding key press. For simplicity sake this demonstration will only support lower case letters and the space bar as input.
Before we get started, take a look at the end result in action:

Plugins and Files
In addition to the jQuery library, we’ll be using one of my favorite plugins to apply easing in our animations. You can grab the latest version on the plugin’s official page. I like to load jQuery from the latest online build, but if you would like to use local copy have one of those ready too.
This project will consist of three different files. In a new folder create jquery-typing.css, jquery-typing.htm, and jquery-typing.js. Once you’ve done that, we’re ready to get started with the code and layout.
Lay Out the Letter Blocks
We’ll start by blocking out the HTML. This demonstration is primarily done in div tags, although you could technically use any number of layout elements for the letter blocks.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.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>jQuery Typing</title> <link rel="stylesheet" href="jquery-typing.css"/> <!--Load up jQuery Library--> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="jquery.easing.1.3.js"></script> <script type="text/javascript" src="jquery-typing.js"></script> </head> <body> <div id="wrapper"> <!--Hidden Letter HUD--> <div id="letter-container"> <div class="letter-box letter-a"><p>A</p></div> <div class="letter-box letter-b"><p>B</p></div> <div class="letter-box letter-c"><p>C</p></div> <div class="letter-box letter-d"><p>D</p></div> <div class="letter-box letter-e"><p>E</p></div> <div class="letter-box letter-f"><p>F</p></div> <div class="letter-box letter-g"><p>G</p></div> <div class="letter-box letter-h"><p>H</p></div> <div class="letter-box letter-i"><p>I</p></div> <div class="letter-box letter-j"><p>J</p></div> <div class="letter-box letter-k"><p>K</p></div> <div class="letter-box letter-l"><p>L</p></div> <div class="letter-box letter-m"><p>M</p></div> <div class="letter-box letter-n"><p>N</p></div> <div class="letter-box letter-o"><p>O</p></div> <div class="letter-box letter-p"><p>P</p></div> <div class="letter-box letter-q"><p>Q</p></div> <div class="letter-box letter-r"><p>R</p></div> <div class="letter-box letter-s"><p>S</p></div> <div class="letter-box letter-t"><p>T</p></div> <div class="letter-box letter-u"><p>U</p></div> <div class="letter-box letter-v"><p>V</p></div> <div class="letter-box letter-w"><p>W</p></div> <div class="letter-box letter-x"><p>X</p></div> <div class="letter-box letter-y"><p>Y</p></div> <div class="letter-box letter-z"><p>Z</p></div> </div> <p class="space-alert">Spacebar!</p> </div> </body> </html>
You’ll realize that certain parts of the code involved are extremely repetitive. Unfortunately there is no real good way around this, so in the mean time just grin and bear it.
Other than the alphabet div tags, there isn’t anything special going on here. We’re loading in the CSS externally, as well as the jQuery library, easing plugin, and our custom javascript file.
If you look at the page right now, it would be a jumbled mess of letters. In the next step we’ll fix this.
Style The Alphabet
Now that we’ve got the structure of the page, let’s get those letter blocks lined up and styled right.
body{
background: #f6f6ed;
font-family: arial, sans-serif;
text-align: center;
margin: 0;
padding: 0;
}
#wrapper{
text-align: left;
width: 960px;
margin: 0 auto;
}
#letter-container{
text-align: center;
margin: 0 auto;
padding: 0;
position: absolute;
top: -205px;
}
.letter-box{
height: 210px;
width: 30px;
position: relative;
background: #191919;
float: left;
margin: 0px 3px 6px 3px;
color: #F7F7F7;
text-align: center;
text-transform: uppercase;
}
.letter-box p{
font-size: 18px;
padding: 170px 0px;
}
.space-alert{
background: #191919;
padding: 20px;
width: 400px;
position: relative;
top: 390px;
margin: 0 auto;
display: none;
text-align: center;
color: #FFF;
font-size: 18px;
}By now you should have a bunch of gray boxes peeking into the window. This would be a terrible place to stop, so let’s add some interactive animation to the mix.
Determine Pressed Key with jQuery
When a key is pressed, jQuery will run through an if statement to determine which key was selected. Keys are identified by their ASCII character value. Under this system, each letter has a number associated with it. There is no quick way to do this. Each case represents a separate letter/value, and the loop below contains 27 possibilities.
Edit and Upgrade: Thanks to our readers James Padolsey and German Rumm. They both pointed out a javascript method of which I was previously unaware, and in this case I love being wrong! The end result is a significantly more compact loop to determine the pressed key. Thanks guys!
Copy this code into your javascript file to give your page the ability to identify lowercase alpha and space bar presses. In the next step we’ll call for an animation when each relevant press occurs.
$(document).ready(function(){
$(document).keypress(function(e){
if (e.which >= 97 && e.which <= 122) {
//Lowercase Alpha
animateLetter(String.fromCharCode(e.which));
}
else if(e.which == 32){
//Spacebar
$(".space-alert").show()
.animate({opacity: 1.0}, 400)
.fadeOut(400);
}
});
});As you may have noticed, only one key is an exception. Just for design variety, the space bar will display a rectangle in the middle of the screen when pressed. The animate event is placed directly in the case instead of firing an external function.
Animate the Selected Letter
You'll notice that we've referenced a function 'animateLetter()' that does not exist. The code below will fix that. Copy it into your jQuery code and then continuing reading below for an explanation.
//Animates pressed key's block
function animateLetter(letter){
$(".letter-" + letter).stop(true,false).animate({top:'190px'},{easing: 'easeInBack', duration:700}).animate({opacity: 1.0}, 300).animate({top:'0px'},{duration:500});
}As you'll recall from the HTML, each block is assigned a class of 'letter-' and then the respective letter (e.g. 'letter-h' represents 'H'). In the above function, the letter of the pressed key is provide as an argument from the keypress event. This letter is used to construct the selector of the proper letter block.
The animation is a relatively straightforward chain of events:
- The animations of the selected letter are all stopped. The reasoning for this has a little bit of depth to it, which you can find explained in further detail in the next section. Sorry for making you skip around!
- The opening animation slides the block down to 190px from the top of the window. This is where the easing plugin comes into play with 'easeInBack'.
- The second animate event is used as a delay.
- The third animate event retracts the block back to its starting position.
A Further Explanation of stop()
If we hold the key down, we do not want the corresponding letter to get stuck in an animation loop. Each keypress should reset the animation queue to keep things smooth. This is done using the stop() method. In the code used in the previous step, I've specified two parameters for stop().
The first says that we want to clear the queue of all animations, and the second says that we do not want the animation underway to rush to the finish. If we had, the boxes would jump around in the every time it was pressed during a previous animation cycle. By keeping this at "false", we make sure animation is always fluid.
Conclusion
Hopefully this tutorial has given you a starting point for using jQuery with keypress events. If there is any confusion or gaps in the explanation, please let me know and I'll fill them in as best I can.
I'm interested to see if anyone has an original new application of this method (or if some already exist!) If you've created something notable, be sure to share it in the comments below!














Discussion
May 20th, 2009 at 12:05 AM
Wow really cool, Zach. I wonder where can we use in web design.
Kawsar Ali’s last blog post..Yet Another 55 High Res Textures to Satisfy Your Design Need
May 20th, 2009 at 2:06 AM
Pretty cool! Can be used in any listing site. Can list your albums/classifieds or something…
May 20th, 2009 at 2:59 AM
wow ! nice effects …. wonderful work … keep it up !
May 20th, 2009 at 3:00 AM
Completely useless but nice to look at. You should let the letters stay longer.
May 20th, 2009 at 3:17 AM
“There is no quick way to do this”
Yes there is
animateLetter( String.fromCharCode(e.which) );
James’s last blog post..jQuery plugin detector
May 20th, 2009 at 3:18 AM
You could replace your 100+ switch with this:
if (e.which >= 97 && e.which = 97 && keycode <= 122) {
animateLetter(String.fromCharCode(keycode));
}
German Rumm’s last blog post..Adobe Flex
May 20th, 2009 at 3:20 AM
Sorry, code didn’t go through last time, will try with HTML entities
if (e.which >= 97 && e.which <= 122) {
animateLetter(String.fromCharCode(e.which));
}
or support both lower and uppercases:
var keycode = String.fromCharCode(e.which).toLowerCase().charCodeAt(0);
if (keycode >= 97 && keycode <= 122) {
animateLetter(String.fromCharCode(keycode));
}
German Rumm’s last blog post..Adobe Flex
May 20th, 2009 at 4:02 AM
I wonder why you prefer too much of case block like that. Even if you don’t know String.fromCharCode() [I didn't know that either
What a shame
], I would rather define an associative array, with keys are keyCodes, and value are the characters. I think that way is much cleaner.
May 20th, 2009 at 9:41 AM
@James and German
I’m always glad to be proven wrong — this case especially. I’ve edited the post with your much simpler solution and credited you two for pointed out the solution. Thanks for all you help! Looks like I need another crash course in Javascript…
May 20th, 2009 at 1:15 PM
Can’t you create the divs that side down from the top programically? Just cycle through an alphabet array, or use php? Otherwise, great tutorial and idea.
CodeJoust’s last blog post..How to StyleIT!
May 20th, 2009 at 3:48 PM
Great tutorial! I’ll definitely give a go!
May 20th, 2009 at 10:55 PM
@Codejoust
I’m sure you could create something to build each div tag for you, but don’t forget that the focus of the tutorial was on the jQuery involved. I chose to write out all of them by hand in order to simplify the explanation required.
May 21st, 2009 at 6:57 AM
Very Nice…….
Srinivas Tamada’s last blog post..Twitter-like Applications with Demos.
May 21st, 2009 at 11:19 AM
That’s really cool, I dig that. Good work!
Tim Wright’s last blog post..Twitter and the Downfall of Social Networking
May 30th, 2009 at 9:23 PM
Oh boy… That’s really nice! I already think how I’ll use it.
Thanks a lot! jQuery Rock!
June 1st, 2009 at 12:48 AM
Very very nice and cool tutorial. Unforgettable jQuery Thanks for sahre.
wpdigger’s last blog post..Theme Membership Sites – Are those really useful
June 9th, 2009 at 9:03 PM
Woah! Cool effect. There are some many things you can now do with jQuery. Keep giving us great examples!
Jad Graphics’s last blog post..10 FREE and Helpful Web Design Resources
June 17th, 2009 at 12:03 PM
“You’ll realize that certain parts of the code involved are extremely repetitive. Unfortunately there is no real good way around this, so in the mean time just grin and bear it.”
Really? Really really?
for (i=0; i<26; i++) {
var let = String.fromCharCode(97+i);
$('#letter-container').append('<div class="letter-box letter-'+let+'’+let.toUpperCase()+”);
}
Took me longer to find the comment form and type my email than it did to to realize how to.
October 23rd, 2009 at 2:17 PM
Interesting idea, but I can’t get it to work in Firefox. Whenever I press a key the Quick Search box pops up at the bottom of the browser window and whatever I type goes in there.
December 28th, 2009 at 8:47 PM
its like a piano, :O
December 30th, 2009 at 7:39 AM
this is sooooooooo coooooooool……… i love this.
Join the Conversation!
Remember: Life's not all doom and gloom, so please keep it constructive. If we've made an error or missed something big, please let us know! Learning is revisions, after all.