Add Events With MooTools

In part one of our MooTools tutorial, we talked about how MooTools web framework is great at helping you write more organized JavaScript code your way. To demonstrate and introduce us to the JavaScript tools, we used MooTools to manipulate HTML and CSS elements on the page.

In part two, we’ll write code that waits for events (such as clicking or typing), then I’ll show how to add your own new functions. At the end of this tutorial, you’ll be able to create a self-formatting telephone number input box that you can start using in forms immediately.

Start With Some HTML

If you’d rather write the code yourself, I’ll also walk you through the code at each step. Add the code to your blank document as we go.

Before we move on to the code, let’s set up the HTML and CSS we’ll be using in the next section. First thing’s first. Start up a typical HTML file. If you don’t have one handy or forgot how to write one, use the blank HTML file from our code library.

Listening to Events

Events are as old as JavaScript. Back before CSS, web developers used onMouseOver and onMouseOut to change graphics when the mouse was hovered. It’s easy to forget with all the shiny web toys available how these simple JavaScript events snazzed up the web.

Now anything interactive that happens with JavaScript is triggered by events. You can access [[Reference:JavaScript Events | all these standard events] and run your own functions every time they occur. In this section, I’ll show a special event just for MooTools and how to add an event to wait for the user to type.

The domready Event

MooTools adds a special event called domready. This can be used to know when it’s okay to initialize the page. The domready event happens when the document object model (DOM) is ready to be accessed.

To understand why this event is necessary, consider these alternatives:

Just put the JavaScript in your page–it will run automatically. This is true. Just toss alert('testing'); between some <script> tags and reload. You’ll get a “testing” message. But what if that line instead attempts to access a form input or a div tag that hasn’t loaded yet? This option can run code too early.

Use the load event — it’s included in JavaScript. Also true. This was long a favorite event of JavaScript developers to avoid running code too early. The downside is that the load event fires when the entire page has loaded, including images and server-timeout-inducing embedded videos. By the time you’re ready to run your JavaScript, the user may have already scrolled down the page and clicked a link. This option can run too late.

To paraphrase a children’s story, we don’t want our code to run too early or too late — we want it to run just right. That’s what the domready event does for us. To use it, just paste this into the <script> tags near the top of your code.

Anything you want to run as soon as possible goes inside the anonymous function we’re creating when the DOM is ready. A common use for this section is to add more events to listen to specific objects, such as a text field. In fact, that’s exactly what we’ll do right now.

Listening for Typing

The domready event is an example of listening for events. Inside the domready event, we can then tell the browser to safely listen for more events, because we know the DOM will be ready for us.

Now we want to listen for typing within the first box and output the latest key that the user typed to the second box. To do this, we’ll need to listen for the keyup event. This happen when the user lets go of a key. There’s also a keydown event, which happens as soon as the user presses a key. The major difference is that keydown lets you know about the key press before it gets to the input box. If you’re comparing the value inside the box, keydown will actually make you one key behind. For this reason, I tend to stick with keyup unless I really need keydown.

This is a very short amount of code, but it does a whole lot. The first thing it does it selects the box with “myinput” as its ID. Then it adds a keyup event and calls an anonymous function whenever the event fires. Inside the anonymous function, it selects the box with “myoutput” as its ID, then sets the entire value of that box to be event.key.

What is event.key, or for that matter that event’ thing I stuck between the parentheses after function? Whenever you make an anonymous function for an event, the first item between the parentheses will always be the event object. That gives you access to lots of great stuff, like what fired the event and, in the case of the keyup and keydown events, which key was pressed (that’s the event.key stuff).

Save and reload your HTML file and try typing in the first box. Watch the second box and you’ll always see the latest key press. Notice anything strange from time to time? If not, you might not be pressing the right keys. MooTools reports when some special keys are pressed, such as enter, delete, backspace, space, and arrow keys. Very useful!

Let’s set events aside for a bit. We’ll get back to them with a vengeance in the final section of this tutorial.

Extending String Operations

As I mentioned in the introduction, MooTools is a JavaScript framework meant for programmers who like to do more than just use software. MooTools is built to make it easy to build on top of it. We saw a bit of that in a previous section when we used the each function. Here, we’re going to extend the string type to make it do something new. That means we’ll be creating a function that you can run on any string as simply as any native string function, like replace.

But first, let’s look at how MooTools has already changed what we can do with strings.

MooTools-specific String Functions

MooTools has extended the String type to do some neat things to be able to change the way a string is formatted.

trim: It’s hard to believe that this isn’t included in standard JavaScript it’s so useful. Take a string and remove any spaces from the beginning and end. So, ” &nbsp Monkeys rule! ” becomes “Monkeys rule!”

clean: Like trim, clean removes spaces from the beginning and end of a string. Also, it makes any double spaces inside a string be only single spaces. So, ” &nbsp Monkeys rule! ” becomes “Monkeys rule!”

capitalize: Make a headline look like a headline by capitalizing the beginning of every word. So, “Monkeys rule, I tell ya!” becomes “Monkeys Rule, I Tell Ya!”

test: Quickly check whether a string contains a second string (pass it as an argument). This uses regular expressions, so you can go wild with the second string, or just make it a normal string.

Write Your Own String Function

Now that we’ve seen how MooTools extended the string type, let’s do it ourselves. For this exercise, we’ll make a new function that performs both the clean and capitalize functions.

To extend the string type, we use the String.implement function. We need to pass an object to it that contains a key and then a function. The code may look confusing, but just follow this pattern:

String.implement({
new_function_name: function(){
// Stuff to do in new function
}
});

The cleancaps function first takes a copy of the string the function is being called on. That string is automatically copied to the this variable. Once we have a copy, we alter it with the clean and capitalize functions. Finally, we return the altered string.

The value in the input box is converted with cleancaps and then set as the new value for the input box.

Now that you have successfully extended the string type, you’re ready for the big finish: autoformatting phone numbers.

Autoformat Phone Numbers on Input

In this final section, we’ll put the pieces together that I’ve shown in previous sections. We’ll be creating an automatically-updating input field that ensures the field has a telephone number in the ten digit format used in the U.S. (for example, 415-555-1212).

To achieve this, we’ll select input boxes, add a keyup event, and call an extended function on the string. I told you–we’re putting it all together.

As a first step, let’s add a couple phone number input boxes to the HTML section of the page:

This code doesn’t do anything if the key the user pressed is delete or backspace. Here we’re using the fancy event.key stuff that MooTools makes available, as we discussed in the events section above. We don’t want to get in the way if the user is removing anything from the input box. We’ll only worry about formatting when the user is typing new text.

Speaking of changing the formatting, this code won’t run unless we extend the string type, similar to the way we did in the previous section. Paste this code into the domready function:

Look for the portions of the number: area code (3), prefix (3), and remaining 4 numbers.

If enough of the number has been added, insert the formatting (parentheses, space, a dash) at the appropriate spots.

That’s it. Save your file and reload. As you type into the first telephone number box, it automatically formats correctly. Sweet!

Add an Event to Multiple Objects

You’ve probably noticed that the second telephone number box is pretty sad. Type into it and it doesn’t format anything. That’s because we haven’t added the event for the second box.

Now, before you run out and include another addEvent for “phonenumber2,” think back to the selection examples earlier in this tutorial. Let’s select with CSS and make both of those phone number boxes autoformat with the same call.

Remove this line:

$("phonenumber").addEvent('keyup', function (event) {

And replace it with this line:

$$(".phone").addEvent('keyup', function (event) {

Now we’re grabbing everything with class=”phone” (note I set that up in the HTML) and applying the same event and formatting to it.

Save and reload. Now both of the phone number boxes bend to your will for proper formatting.

Even better, you’re now using MooTools the way its creators intended. Write code once, but use it many times. If you always include this code on a form page and always give your phone number fields a class of “phone,” then your phone numbers will be forever formatted correctly. And you don’t have to write that code ever again. That’s powerful.

Where To Go From Here

For starters, you probably have a lot of JavaScript to rewrite, don’t you? With your newfound efficient coding with MooTools, I’m seeing lots of ugliness in my old code.

You’ll also probably want to learn more about MooTools. Though it’s a great framework, the documentation is somewhat lacking. However, CNET has an excellent “Mootorial” that does a good job of clearly explaining the concepts of each portion of MooTools.