Make an Animated Alphabet using Keypress Events in jQuery

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:
Keyboard powered animation!

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.

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.

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.

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.

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:

  1. 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!
  2. 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’.
  3. The second animate event is used as a delay.
  4. 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!

Posted Tuesday, May 19th, 2009 · Back to Top

SPONSOR

Add Comment

29 Comments 27 Mentions

  1. Kawsar Ali Author Editor

    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

    ·

  2. Sai Prasad Kothapalle Author Editor

    Pretty cool! Can be used in any listing site. Can list your albums/classifieds or something…

    ·

  3. saurabh shah Author Editor

    wow ! nice effects …. wonderful work … keep it up !

    ·

  4. Anthony Alexander Author Editor

    Completely useless but nice to look at. You should let the letters stay longer.

    ·

  5. James Author Editor

    “There is no quick way to do this”

    Yes there is :)

    animateLetter( String.fromCharCode(e.which) );

    James’s last blog post..jQuery plugin detector

    ·

  6. German Rumm Author Editor

    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

    ·

  7. German Rumm Author Editor

    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

    ·

  8. Huy Dũng Author Editor

    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.

    ·

  9. Zach Dunn Author Editor

    @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…

    ·

  10. CodeJoust Author Editor

    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!

    ·

  11. Lex Garey Author Editor

    Great tutorial! I’ll definitely give a go!

    ·

  12. Zach Dunn Author Editor

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

    ·

  13. Srinivas Tamada Author Editor

    Very Nice…….

    Srinivas Tamada’s last blog post..Twitter-like Applications with Demos.

    ·

  14. Tim Wright Author Editor

    That’s really cool, I dig that. Good work!

    Tim Wright’s last blog post..Twitter and the Downfall of Social Networking

    ·

  15. Juarez P. A. Filho Author Editor

    Oh boy… That’s really nice! I already think how I’ll use it. :) Thanks a lot! jQuery Rock!

    ·

  16. wpdigger Author Editor

    Very very nice and cool tutorial. Unforgettable jQuery Thanks for sahre.

    wpdigger’s last blog post..Theme Membership Sites – Are those really useful

    ·

  17. Jad Graphics Author Editor

    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

    ·

  18. Joshua T Corbin Author Editor

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

    ·

  19. Dale Author Editor

    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.

    ·

  20. Gabriel Author Editor

    its like a piano, :O

    ·

  21. Maverick Author Editor

    this is sooooooooo coooooooool……… i love this.

    ·

  22. Anupam Sen Author Editor

    jQuery is fun…
    for animation I’ve also used jQuery for my website.. check out…

    ·

  23. alpaproductions Author Editor

    I’ve seen something similar to this but with a timer and all that is actually a GAME! This would be pretty useful and a huge step forward towards that. Nice!

    ·

  24. ashok Author Editor

    hey can i use this plgin in my portfolio website ?

    ·

  25. Sulaman Author Editor

    Its nice and cool,

    a small feedback, you can add the below line using js.
    “A”

    ·

  26. jose manuel pizarro Author Editor

    esto no corre

    ·

  27. behzad Author Editor

    This Post is Very nice for me!
    Thank’s a lot dear zach.

    ·

  28. yingoabd Author Editor

    Hi, dear, how are you? Today, I would like to introduce this site is reliable to offer you cool items, like jordans, hats, handbags and so on, all the items have excellent design and standard quality! Maybe you will like shopping here, just have a try!![url=http://www.jordanscheap3.com]air jordans[/url].

    ·

  29. sunil Author Editor

    gr8 work and creative

    ·

 

Build Internet by One Mighty Roar. Since 2008.