30 Days of Mootools 1.2 Tutorials - Day 4 - Functions

- Sam

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…

Download a zip with everything you need to get started

Including the Mootools 1.2 core, an external javascript file, a simple html page and a css file.

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

Utilities/DomReady
Number.toInt()
Number.limit()
Array.rgbToHex()
Element.setStyle()
Element.addEvent()

Tomorrow’s Mootools 1.2 Tutorial - Events

Check in tomorrow for Day 5 - Events.

Tutorial Request or Questions

We’re going to be ramping up to some more in-depth stuff pretty soon. As always if you’ve got any questions about the code here or any future areas of mootools you’d like us to cover we’d love to hear from ya.

Bookmark and Share

Comments (13)
  1. Ryan Rampersad


    This was pretty lacking in actual mootools but it's pretty good on functions. Not many people know you can pass functions as arguments.
    (As for the functions in mootools, don't forget periodical and delay.)
  2. benjamin


    Again, I love this online service that you all are providing. This is the first site that I check each morning. I've been eager to cross into the js world. Thanks for making this fun and understandable.
  3. RobertK


    I have been a fan of MooTools since 1.0, and I'm very glad to have found your series of tutorials. I have been in need of a quick review, since I haven't used the library for about a year.

    Keep up the nice tutorials.
  4. Troy


    @1 - Thanks Ryan, we will be sure to do an entry on creating timed events and functions.
  5. Vin Thomas


    Another great day!
  6. Andreas


    You can also chain function, so you can write:

    var blue = $('blue').get('value').toInt().limit(1, 255);
  7. Sam


    yeah, I also realized that it needs a final value check before it can be safely pushed through rgbToHex(), something along the lines of :

    if ($type(red)!= 'number'){red = 0;}

    Then theres also dealing with the colors in array from the beginning, I'm thinking about building this chunk as we go over useful material.

    Is there anything else you can think of to slicken it up?
  8. Sam


    Played with shortening it down, got this :


    var colors = ['246', '112', 'reset_me'];
    colors.each(function(color, index){
    colors[index] = color.toInt().limit(0, 255);
    if ($type(colors[index])!='number'){colors[index] = 0;}
    });

  9. Kent Pilkington


    Regarding the use of anonymous functions vs. declaring them and then calling them from the domready event, there are a couple of reasons to consider the second approach, both related to working around deficiencies in Internet Explorer.

    I've not quite been able to nail down exactly what triggers this, but in some cases setting the domready event in the page head can cause IE to flash an "operation aborted" (or somesuch) error and then go to a screen indicating a DNS resolution error. Not all installations of IE will experience it (e.g. mine do not, but my co-worker's does).

    The most reliable solution I've found is to move the domready-setting code to the very end of the page, but you may want to have the function assignment and other declarations in the page head (or in .js files referenced there, etc.).

    In addition, I've had instances where having the domready code call an anonymous function triggered the same IE bug, but when changed to a declared function, the bug was not triggered. I haven't consistently reproduced this one, so consider it along the lines of a bigfoot sighting, but if your site needs to support a broad base of target systems, I think you are better off not mixing anonymous functions and the domready event. (Once the page is loaded, however, there appears to be no big difference.)
  10. Sam


    Hey Kent,

    Thanks for heads up, I'm curious if you have any idea whether it's the placement of the domready in the head that's causing the bugs or if it's a matter of the order of execution?

    The first (somewhat-plausible) explanation for this behavior that springs to mind is that IE is somehow choking on the functions in the domready before it can get to the function declarations in the rest of the script, if that's the case then I think having the domready event after the function declarations should let me sidestep that one. *fingers crossed*

    Also, would you happen to remember what version/version range of IE you were seeing this behavior in?
  11. Louis


    Thanks for this very fine tutorial !

    Also, I've seen you accept suggestions, so, I think you should say some word on good practices about variables scope and encapsulation, as it has become pretty standard to use a lot of different origins JavaScript on the same page.
  12. Troy


    @11 - That's a very good suggestion. We will be sure to talk about those issues later in the series. For anyone interested, there is a link on the subject (as well as a few others related to javascript) at Louis's blog:

    http://64.233.179.104/translate_c?hl=en&langpair=fr|en&u=http://nophysic.com/2008/08/24/quelques-lectures-interessantes-autour-de-la-programmation-en-javascript/&usg=ALkJrhhPmbwr0HeYr8YfYb6QHXBl3fmLRA

    (we are currently messing with our comments code and will have links working soon)
  13. Kent Pilkington


    @Sam - Moving the domready assignments from the HTML head to the end of the HTML body is the generally promoted workaround (I've seen it mostly in 6.5, but also in 7). For example, Google recommends doing this if your page integrates Google maps. It almost certainly has something to do with the order in which things happen. I think IE sees that there is code in the head tag messing with the DOM before it is "fully cooked" and panics under the assumption that it is being tampered with by outside and mysterious forces (i.e. something other than the HTML being read off the page body). :-) Perhaps not an exact technical description, but it seems consistent with my observations.


Leave a Reply