Fork me on GitHub

30 days of
MooTools


30 days of MooTools is a collection of tutorials to learn to use the MooTools javascrit library, first published in 2008 by ConsiderOpen.

The lessons are actually 23, as they where interrupted after this day.

As the original site is currently offline, the tutorials have been collected using the Wayback Machine to make them available to everyone interested in learning to use MooTools.

The tutorials are based on MooTools 1.2 so some parts could be deprecated and they should be updated and expanded based on the new MooTools versions.

The copyright (and gratitude) for the original lessons is hold by ConsiderOpen.




Idea Paolo Manganiello. Licence CC 3.0.

Functions and Mootools 1.2

Welcome to day 4 of the 30 Days of Mootools. If you haven’t already, go check out the previous Mootools Tutorials in the series. Today we’re taking a step back from the Mootools to go over the basics of functions in javascript.

Keeping with the Mootools theme however, you should be aware of where to place functions for use with Mootools. Previously we’ve been placing all of our example code within the domready function. When dealing with functions you want to place them outside of the domready loop. Functions aren’t executed until you call them from within the domready.

Generally it’s a good idea to try and keep as much of your function code outside of the page body all together and call it in through a javascript include. When just monkeying around with code though, I find it easier just to keep everything on the same page. We’re using the following convention for these tutorials:

<script type="text/javascript">
	/* 
	Function definitions go here
	*/
 
	window.addEvent('domready', function() {
		/* Calls to functions go here */
	});
</script>

All the examples follow this format, which results in the function being executed when the page loads. They also all have example buttons beneath them which you can press to see the results. This is accomplished through the using Mootools event handlers which we’ll be talking about tomorrow.

The Basics

There are a few ways to define functions in javascript—since we’re focusing on Mootools we’ll be using their preferred methodology. The example below is about as basic as a function can get. We declare a variable named simple_function and define it as a function:

var simple_function = function(){

Then we add an alert to be run when the function is called:

alert('This is a simple function');

Finally, we close the function definition with a closing curly bracket:

}

This closing bracket is one of the easiest things to overlook, and can often times be an incredible pain to track down—it’s a good idea to be mildly obsessive about double checking the closing of your function definitions.

It’s all rolled together in the example below. After declaring the function, we’re adding a call to the function to the domready event that will execute on page load. Press the button beneath the example to see the result of calling simple_function(); .

//Define simple_function as a function
var simple_function = function(){
	alert('This is a simple function');
}
 
window.addEvent('domready', function() {
	//Call simple_function when the dom(page) is ready
	simple_function();
});

Single Parameter

While having a chunk of code you can easily call from anywhere is useful, it’s even more useful when you can pass it parameters (information) to work with. To use parameters with functions, you need to add a variable name in the parenthesis after function like so:

var name_of_function = function(name_of_the_parameter){
    /*function code goes here*/
}

Once you’re done, the variable is available inside the function for use. While you can name a parameter pretty much anything you want, it’s a good idea to make your parameter names as descriptive as possible. So for instance, if you were passing a parameter that held the name of a town, calling the parameter town_name would be preferable to something more vague (like user_input).

In the example below, we’re defining a function that takes a single parameter (called parameter) and sends out an alert containing the parameter. Note that while the first part of the message is surrounded by single quotes, the parameter is not. When you want to use parameters in combination with hardcoded strings, you need to join them together with the + operator as shown below:

var single_parameter_function = function(parameter){
	alert('the parameter is : ' + parameter);
}
 
window.addEvent('domready', function(){
	single_parameter_function('this is a parameter');
});

Multiple Parameters

Javascript doesn’t limit the amount of parameters you can define for a function. It’s generally a good idea to try and keep the number of parameters you pass to a function to a minimum for readability’s sake. Multiple parameters in a function definition are separated by commas, and otherwise behave exactly the same as a single parameter function. The example function below takes two numbers, and places their sum into the variable third_number like so:

var third_number = first_number + second_number;

Then the + operator is used in a slightly different fashion to join the results together into a text string:

alert(first_number + " plus " + second_number + " equals " + third_number);

While this may seem confusing at first, it’s actually pretty straightforward. If you use + between numbers, you’re adding them together. If you use + between any combination of numbers and strings you’re joining all the input into a single string.

var two_parameter_function = function(first_number, second_number){
	//Get the sum of first_number and second_number
	var third_number = first_number + second_number;

	//Display the Results
	alert(first_number + " plus " + second_number + " equals " + third_number);
}
 
window.addEvent('domready', function(){
	two_parameter_function(10, 5);
});

Returning a Value

Displaying the results of a function in an alert can be helpful, but sometimes you’ll want to take the result and use it somewhere else. To accomplish this you need to make use of return within the function. The example below functions pretty much the same as the previous example, except instead of sending out an alert, the script returns the sum of the two numbers here :

return third_number;

You’ll notice that we’re doing more in the domready as well. In order to display this value, we’re assigning the functions return value to a parameter named return_value and then displaying an alert.

var two_parameter_returning_function = function(first_number, second_number){
	var third_number = first_number + second_number;
	return third_number;
}

window.addEvent('domready', function(){
	var return_value = two_parameter_returning_function(10, 5);
	alert("return value is : " + return_value);
});

Functions as Parameters

If you look at the Mootools domready code we’re wrapping things in, you’ll notice that you’re passing a function as a parameter :

window.addEvent('domready', function(){
	/*code*/
});

A function that is passed as a parameter like this is referred to as an anonymous function:

function(){
	/*code*/
}

In the Day 1 comments Boomstix pointed out an alternate method for using the domready without using anonymous functions. Doing so would look something like this :

//Build the function to be called on domready
var domready_function(){
	/*code*/
}
 
//Assign the function to the domready event
window.addEvent('domready', domready_function);

I’m not aware of any significant difference between the performance or functionality of the two methods, so I believe this is essentially a stylistic choice. We’re going to be sticking with our method for now, but if anyone out there knows otherwise please let us know.

Examples

To whet your appetite for tomorrow (and make up for the lack of mootools today), I present a somewhat pointless function to let you change the background color of this page on the fly :

var changeColor = function(){
	//Use get to retrieve the color 
	//values from the text boxes
	//( http://docs.mootools.net/Element/Element#Element:get )
	var red   = $('red').get('value');
	var green = $('green').get('value');
	var blue  = $('blue').get('value');
 
	//Make sure everything is an integer
	//( http://docs.mootools.net/Native/Number#Number:toInt )
	red   = red.toInt();
	green = green.toInt();
	blue  = blue.toInt();
 
	//Make sure each number is between
	//1 and 255, rounding if needed
	//( http://docs.mootools.net/Native/Number#Number:limit )
	red   = red.limit(1, 255);
	green = green.limit(1, 255);
	blue  = blue.limit(1, 255);
 
	//Get the Hex Code
	//( http://docs.mootools.net/Native/Array/#Array:rgbToHex )
	var color = [red, green, blue].rgbToHex(); 
 
	//Set the Background color of the page
	//( http://docs.mootools.net/Element/Element.Style#Element:setStyle )
	$('body_wrap').setStyle('background', color);
}
 
var resetColor = function(){
	//Reset the background color to white
	//( http://docs.mootools.net/Element/Element.Style#Element:setStyle )
	$('body_wrap').setStyle('background', '#fff');
}
 
window.addEvent('domready', function(){
	//Add click events to the buttons (more on this tommorrow)
	//( http://docs.mootools.net/Element/Element.Event#Element:addEvent )
	$('change').addEvent('click', changeColor);
	$('reset').addEvent('click', resetColor);
});

Red :

Green :

Blue :

To Learn More…

More on Javascript Functions

Quirksmode on Javascript Functions

I’m a little light on good resources for on Javascript functions, if anyone knows of good ones please send them my way.

Example Documentation

Tomorrow’s Mootools 1.2 Tutorial - Events

Check in tomorrow for Day 5 - Events.