File Under: Frameworks, JavaScript

Get Started With MooTools

Programming with JavaScript can sometimes make me feel disorganized. I end up with bits of code floating around for various purposes. What was missing for a long time was some way to keep everything organized.

Now we’re being helped out by JavaScript frameworks, like MooTools, Prototype and JQuery. These frameworks sit on top of JavaScript and makes some common tasks a whole lot easier. When you use MooTools, as you will in this tutorial, you’re still writing JavaScript, but hopefully it’s a little more organized.

If you are still a beginning programmer, other frameworks might be a better choice. For example, see our jQuery tutorial. The way MooTools does things is a bit more for programmers than designers.

The MooTools way of doing things focuses on helping you not write the same thing over and over again. While the core of the library doesn’t do everything for you (as some frameworks do), MooTools gives you the structure to do it for yourself once, then use is many times.

In this tutorial I’ll introduce you to the MooTools way of writing JavaScript. Then we’ll select objects from the page in a few different ways.

Let’s get going and learn how to use the MooTools JavaScript framework.

Contents

  1. What You Need
  2. Start With Some HTML
  3. Be Selective With MooTools
    1. Select by ID
    2. Select by Class
    3. Select by Tag
    4. Selecting the First Object of Many
    5. Calling Your Own Function on Results
  4. Where to Go Next?

What You Need

  • Knowledge of HTML and CSS
  • Intermediate knowledge of JavaScript
  • A copy of a MooTools source file. Name it mootools.js (at least for these examples)

Start With Some HTML

Before we get to using MooTools, let’s get the example HTML ready to go. Copy the code below into an empty document in the same directory as your mootools.js:

<html>

<head>

	<title>Testing MooTools</title>

	<script src="mootools.js"></script>

	<style>

		// CSS goes here

	</style>



	<script>

		// JavaScript goes here

	</script>

</head>

<body>



</body>

</html>


Opened in a browser, the above is blank. That’s because it’s only a starting place for the code we’ll be adding into it. Even though it’s empty, MooTools is being loaded. Check out the script line where src="mootools.js". This line will autmatically load the MooTools source JavaScript in the file.

Another note about scripts. The JavaScript code we create in this tutorial will be written alongside HTML within one main .html file. Normally, we’d link to an external JavaScript file instead the same way we link to the MooTools source code. The same goes for our CSS style, which we’ll put in the document between the style tags. Normally, all of these files would be in another directory too. For this tutorial I’m including scripts and styles inline (with the exception of mootools.js) because I want to make the code easy to read and manipulate.

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

Add this between the body tags:

<div id="container">

<span>SPAN<br />No id</br />No class</span>



<span class="test" id="second">SPAN<br />id="second"</br />class "test"</span>

<div class="test">DIV<br />No id</br />class "test"</div>

</div>



<p>

<strong>Toggles:</strong>

</p>


And put this between the style tags:

#container div, #container span

{

	width: 150px;

	height: 150px;

	display: block;

	float: left;

	border: 1px solid black;

}

#container .highlight

{

	border: 3px solid orange;

}

p

{

	clear: left;

}

p input

{

	display: block;

}


Reload the HTML file you created and you’ll see a few squares on your screen. Yay! Now let’s bring on the MooTools magic.


Be Selective With MooTools

At the heart of every JavaScript framework is a way to select objects on the page. We need to access these objects in order to do anything with them. In this section, I’ll show some ways to select objects using MooTools.

To follow along, you can grab the code now from our code library.

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 HTML document as we go.

Select by ID

To select a single object using its ID, you just pass that ID to the dollar sign function. For example, our basic HTML file has a div with id="second". To select that div, we just need this one line: $("second")

To test this out in our example HTML file, add the following underneath the “toggles” section near the bottom of the HTML:

<input type="button" onClick="javascript:test_byid();" value="id='second'" />


This line adds a button to the page that, when clicked, calls the test_byid() function. Where is that function? We need to add it between the script tags in your example HTML file:

function test_byid()

{

	$("second").toggleClass("highlight");

}


Reload the file and click the new button. The second span (the one with id="second") highlights.


Select by Class

Selecting by ID is useful, but perhaps more useful is being able to select by CSS class. In this case, we’re selecting more than one item. We use the double dollar sign function. The syntax is similar to CSS, where we put a period in front of the class name. To select an object of class “test,” use this code: $$(".test")

Let’s test it in our example HTML file. Here’s the code for the testing button:

<input type="button" onClick="javascript:test_byclass();" value="class='test'" />


And now the JavaScript, which you should paste below the previous function:

function test_byclass()

{

	$$(".test").toggleClass("highlight");

}




Reload the file and click the new button. The two right boxes (the ones with class="test") highlight.

Select by Tag

The last example used CSS to grab objects by class name. You can do the same thing by tag name. Just put the tag name inside the double dollar sign function, like so: $$("span")

In our example HTML file, paste this code for the button to test getting objects by tag:

<input type="button" onClick="javascript:test_bytag();" value="tag is 'span'" />


And the JavaScript function:

function test_bytag()

{

	$$("span").toggleClass("highlight");

}


Reload and click the new button. You’ll see the two left boxes (the ones that are span tags) highlight.

You can use more specific CSS, too. Change $$("span") to $$("span.test") in the test_bytag function and you’ll only select the object that is a span tag with class="test".


Selecting the First Object of Many

Sometimes you don’t want every result, but instead just want the first. There are several ways to achieve this, but the easiest is through the first-child psuedo-selector. To use it, just add a color and first-child after the CSS-like call: $$("span:first-child")

Here’s the HTML:

<input type="button" onClick="test_byfirstresult();" value="the first object where tag is 'span'" />


And the script:

function test_byfirstresult()

{

	$$("span:first-child").toggleClass("highlight");

}


Reload and click the new button. You’ll see just the far left box (the first span tag) highlight.


Calling Your Own Function on Results

Sometimes straight MooTools isn’t enough to get what you want. That’s when it’s time to harness some of its extensibility. To iterate through all the results, you call the each function. For example, $$("span").each() will go through every span object.

Check out the code and then we’ll look at the specific pieces.

Here’s the HTML:

<input type="button" onClick="test_byfunction();" value="tag is 'span', but id is not 'second'" />


And the script:

	function test_byfunction()

	{

		$$("span").each(function(spanobj) {

			if (spanobj.id != 'second')

			{

			  spanobj.toggleClass("highlight");

			}

		});

	}


You’ll notice there’s a big chunk of stuff inside the parentheses of the each function. That’s an anonymous function, written inline. You cannot call it directly (it has no name!), but it still acts like a normal function. In this case, it is called automatically with each object found passed as an argument.

Inside the function, it checks the ID of the object it was passed. If the ID is not “second,” we highlight the object the same way we have in previous examples.

Reload and click the new button to see this in action. Just the far left box (the only span that does not have id="second") highlights.

Where to Go Next?

You now know the basics of selecting in MooTools and have seen an anonymous function. Both of these will play a large role in the examples throughout the next part of this tutorial.

In part two of our tutorial, we talk about events and how MooTools handles them. 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, you’ll be able to create a self-formatting telephone number input box that you can start using in forms immediately.

From the MooTools Tutorial series

Lesson 1: Get Started With MooTools
Lesson 2: Add Events With MooTools