Você está na página 1de 48

Advanced Web

Programming
Jaume Aragonés Ferrero

Department of Software
and Computing Systems
Advanced Web Programming

A compact JavaScript framework

MOOTOOLS
Advanced Web Programming

Index
• What is MooTools?
• Where to find?
• How to download?
• Hello World example.
• A little bit of knowledge.
• Creating a console.
• Form data validation.
• Exercises.
Advanced Web Programming

What is MooTools?
• MooTools is a JavaScript framework
– MooTools is a lightweight abstraction
layer between the browser and the
code you write.
• It is Object-Oriented
• It allows to write cross-browser code.
• It respects standards and it's
extensively documented.
• It is released under Open Source MIT
license
Advanced Web Programming

What is MooTools?
• Wikipedia:
– MooTools is an open source,
lightweight, modular object-oriented
programming JavaScript web
application framework.
– It includes built-in functions for
manipulation of CSS, DOM elements,
native JavaScript objects, Ajax
requests, and more.
Advanced Web Programming

What is a Framework?
• It is an abstraction in which common code
providing generic functionality can be
overriden by user code providing specific
functionality.
• The idea is similar to SW libraries: they are
reusable abstractions of code in a well
defined API.
• In other words: it is a SW layer between the
programmer and the developing platform in
order to help building programs.
Advanced Web Programming

What can I do?


• Some examples of things you can do with
MooTools:
– Code Javascript easily: Mootools features
improve Javascript capabilities.
– Code Client-Side Object Oriented: Create your
own classes with Javascript.
– Work with JSON: sending and reciving data.
– Create FX with Javascript: user interaction,
dinamic menus, transitions (tween, morphs),
slides, scrolls, etc.
– Work with AJAX and interact with your server
scripts.
Advanced Web Programming

What is JSON?
• JSON stands for Javascript Object
Notation
• It is a data interchange format
• JSON information is in text format
• It is supported by many languages:
Javascript, C, PHP, ASP.NET, Java,
Python, etc.
• JSON data takes this form:
Advanced Web Programming

Where to find?
• http://mootools.net, home page.
• http://mootools.net/download,
download page.
• http://mootools.net/docs,
documentation page.
• http://www.mootorial.com/wiki, a
good tutorial
Advanced Web Programming

How to download?

Go to www.mootools.net/download

Here you can download the MooTools
core.

Use the uncompressed version for
development and the compressed one
for the real site.

The core download includes: library
base, ajax working, effects, classes and
extensions.
Advanced Web Programming

How to download?

The download page:
Advanced Web Programming

How to download?

The 'more Builder' link allows you to get
the MooTools Add-ons:

Classes

Native Objects, Element classes

Forms

FX, Drag, Request

Utilities, Interface, etc.

Just check the scripts you want, choose a
compression type and then donwload the
include file.
Advanced Web Programming

How to download?

The 'more Builder' page with some
options:
Advanced Web Programming

How to download?

Tip: choose the whole library for
development only if you don't know
which script you will need to use.

Compression types remove extra blank
spaces and rename variables in a
shorter way, making a much smaller file.

YUI compressor is the most efficient.
It will be very useful when releasing
your code.
Advanced Web Programming

Before start working...


• Firebug:
– Extension for Firefox
– allows debugging, editing, and
monitoring CSS, HTML, DOM, and
JavaScript code, and provides other
Web development tools.
– https://addons.mozilla.org/en-
US/firefox/addon/1843
Advanced Web Programming

Before start working...


• Web developer toolbar:
– Extension for Firefox
– adds a menu and a toolbar with
various web developer tools.
– https://addons.mozilla.org/en-
US/firefox/addon/60
Advanced Web Programming

How to add to my pages


• It's easy, just include the MooTools file
with the 'script' tag.
<script type=”text/javascript”
src=”path/to/MooTools.js”></script>
• You can also include your own javascript
files or even code javascript lines inside
the web page.
• The MooTools file include must be the
first one in your web page.
Advanced Web Programming

How to add to my pages


• Here is an example document
<!DOCTYPE ...>
<html ...>
<head>...
<script type=”text/javascript”
src=”path/to/MooTools.js”></script>
<script type=”text/javascript”
src=”path/to/MyJSFile.js”></script>
<script>My own Javascript code</script>
</head>
<body>...</body>
</html>
Advanced Web Programming

Hello world example


• First, write a 'Hello world' page with only HTML.
• After, write a second page using javascript&DOM.
• Finally, let's display a 'hello world' message from
MooTools code:
<script>
window.addEvent("domready", function(){
$('text').appendText("Hello World! (from
MooTools code!).");
});
</script>
• And the body code:
<p id="text"></p>
Advanced Web Programming

Hello world example


• AddEvent: allows to match a handler
function to an HTML element event.
• Domready: is the event triggered when
the DOM is ready and it has loaded all
code and data.
• $('id-of-tag').method-or-property: when
we want to access to an element's
method or property.
• AppendText: a method allowing us to
add some text inside an element.
Advanced Web Programming

A little bit of knowlegde


• http://mootools.net/docs/core/Element/Element
• $('theID'), select one element identified by 'theID'.
• $$('something'), select one or more elements
matching 'something' string.
– It returns an array or collection of elements
– You can use tags names, classes, identifiers, etc.
• Event 'DomReady', It fires when the DOM (and all of
its objets) is ready. So, in this moment you are sure
you can work with all objects in the page.
– This event is only available from the window
Element.
Advanced Web Programming

A little bit more of knowlegde


• $('myID').getElement(),
• $('myID').getElements()
• $('myID').getElementsById()
• Get children elements from our 'myID'
element.
• $('myID').get('property')
• $('myID').set('attribute', 'value')
– Set a value into a property of our
'myID' element.
Advanced Web Programming

A little bit more of knowlegde


• myElement.erase(property), deletes the
element's property.
• myParent.adopt(newChild, ...)
– insert 'newChild' as child of 'myParent'
element.
• myElement.inject(element2, where)
– Insert 'myElement' in 'where' position
from 'element2'.
• Others: appendText, dispose, replaces,
etc.
Advanced Web Programming

Core functions
• http://mootools.net/docs/core/Core/Core
• $$('aTag').each(new function {something...})
– Calls the function for each element in the
collection retrieved by $$.
• $chk, $defined, $type, $random, etc.
• $A, creates an iterable array.
• $H, creates a hash table (=Hash())
Advanced Web Programming

Creating a console
• Let's create a 'console', that is, a layer allowing us to put
some text in order to debug or to display results of some
actions.
• Here is the needed code:
function toConsole(theText){
if (!$('console')) {
var element = new Element('div',
{'id':'console'});
$$("body")[0].adopt(element);
}
var element = new Element('div');
element.appendText(theText);
$("console").adopt(element);
}
Advanced Web Programming

Creating a console
• You can write this code directly inside the HTML
file or put it into an extern javascript file, and
then include it from the web page (the best
choice).
• Once you have typed the previous code, let's test
it by creating a new page with
– a command button (<input type=”button”...)
with an 'id' attribute.
– coding the 'window.onload' event and
attaching a handler function to our button's
'onclick' event.
Advanced Web Programming

Creating a console
• The button code:
<input type="button" value="click me!"
id="write" />
• The handler code:
window.onload = function() {
var button=$('write');
button.onclick=function() {
toConsole('You have clicked on
the button, so I am writing in the
console...');
return false;
}
}
Advanced Web Programming

Try to do yourself...
• What happens if you click the button
several times?
• Modify the code in order to put a
counter counting the times the button is
clicked.
• Modify the code in order to clean the
console each time the button is clicked.
Advanced Web Programming

Defining classes
Var myClass= new Class({
MyAttr: 'value',
...
Initialice: function(...){
...},
MyMethod: function(...) {
...}
});
Var myObj = new myClass(...);
myObj.MyMethod(..);
Advanced Web Programming

Form data validation


• One of the most useful things we can do with javascript
is to validate correctness of HTML forms.
• Using MooTools we can also validate HTML forms.
• We can build a class containing methods for validate
every type of field in our forms:
– Mandatory fields (text boxes, selects, radiobuttons)
– Text boxes containing specific data (numeric, date, an
interval of values, etc.)
– Text boxes and text areas with a maximum length.
– And any other kind of validation.
Advanced Web Programming

Form data validation


• Let's create our own form validation
class:
– First, we will design a one
mandatory field form called user
name, and a command button to
send the form data.
Advanced Web Programming

Form data validation


• The next is to implement our class
var cTestOK = new Class ({
error1: 'This field cannot be empty.',
isEmpty: function(pField){
var field = $(pField);
if (field.get("value")=="") {
alert(this.error1);
return true;
This class has
} else { - one attribute (a message
return false; error)
} - and one method: a function
} receiving a field name to test its
emptyness.
});
Advanced Web Programming

Form data validation


• Finally, we are going to handle the onclick button event to
trigger our class method.
window.addEvent("domready", function(){
var oTesting = new cTestOK("myForm");
$("sending").addEvent("click", function()
{oTesting.isEmpty("pName");});
});
• This instruction allows us to link a function to the onclick
button event.
• In this way, we will invoke the method 'isEmpty' of our
class and we send it, as an input argument, the name of
the field we want to test its correctness.
Advanced Web Programming

Try to do yourself...
• Add a select control with a product list.
– This field is also mandatory.
• Add a new text field to the form asking for the amount of
products the user wants to buy.
– This field will have a default value: 1.
– This field is also mandatory.
– This field is a numeric value starting from 1.
• Finally, add a textarea field asking for any comment
about the user order.
– This field is optional.
– This field has a maximum lenght of 200 chars.
Advanced Web Programming

References
• Webs:
– mootools.net
– www.mootorial.com
– json.org
– wikipedia.org
• Books:
– MootTools Essentials, Aaron
Newton. Apress / firstPress. 2008
Advanced Web Programming

Exercices
• Managing select options: changing
options depending on other select
value.
• Accordion FX.
• Tween FX.
• Sorting lists
• A game: guess the words I've though
about...
Advanced Web Programming

Managing select options


• Let's make a web page with two
select fields, the content of one
of them depending on the
other's selected option.
• Suppose we have two selects
like shown in the figure:
Advanced Web Programming

Managing select options


• First of all, we declare an array of cities for
each country in the select.
var theWorld = [
$H({1: 'Warszawa', 2: 'Bialystok', 3:
'Lublin', 4: 'Krakow'}),
$H({1: 'Madrid', 2: 'Barcelona', 3:
'Alicante', 4: 'Valencia'}),
$H({1: 'San Francisco', 2: 'Washington',
3: 'New York', 4: 'Los Angeles'})];
Advanced Web Programming

Managing select options


• Next, we attach a handler to the
'onchange' event of the country select.
window.addEvent("domready",
function(){
var country = $("countries");

country.addEvent("change", function()
{putCities();});
});
Advanced Web Programming

Managing select options


• Finally, we implement the handler.
• It will change all the options in the
city select loading the selected
country cities.
– Test if the selected country is the
'non-selection' value '-1', and
decide what to do if so.
Advanced Web Programming

Accordion menu
• Let's create a dinamic menu with
expanding/contracting options, a.k.a. Accordion
menu.
• First: type the HTML code of our menu.
– The first level options
– For each first leve option, type its second level
options.
• Second: label all the first level options with a
CSS class, i.e.: level1.
– Do the same with each element containing the
second level options: 'level2' CSS class.
Advanced Web Programming

Accordion menu
• Finally: create and Accordion object
in the 'Domready' event.
window.addEvent("domready",
function(){
var myAccordion = new
Accordion($$("li.level1"), $$
("ul.level2"));
});
Advanced Web Programming

Tween FX
• Tween FX change a CSS property from one value to
another.
• We can set the duration, start and end values, property
to change, etc.
window.addEvent("domready", function(){
var myFX = new Fx.Tween($('myP'), {property:
'left', duration: 3000})
myFX.start(0, 100);
});
• And in the Body
<p id="myP" style="position: absolute; left:0px;
top:0px;">Hello world!</p>
Advanced Web Programming

Sorting lists
• Design a list of items with HTML.
• Add two buttons to each item.
– One of then will by the up button
and the other the down one.
• Implement client-side code with
MooTools to add the necessary
functionality
Advanced Web Programming

Sorting lists
• Design a list of items with HTML
<div id="toSort">
<div id="1" class="item">First item</div>
<div id="2" class="item">Second Item</div>
<div id="3" class="item">Third item</div>
<div id="4" class="item">Fourth item</div>
</div>
Advanced Web Programming

Sorting lists
• Add the up&down buttons
• Each item will chage as follows:
<div id="1" class="item">
<div class="img UP"></div>
<div class="img DW"></div>
First item
</div>
Advanced Web Programming

Sorting lists
• Define some CSS styles to adjust the layout:
.img {
float:left;
width: 17px;
height: 17px;
padding: 2px;
background-repeat: no-repeat;
background-position: 0px 0px;}
.UP { background-image: url('up.png'); }
.DW { background-image: url('down.png'); }
.item { clear: both; vertical-align: top; }
Advanced Web Programming

Sorting lists
• Program the sorting functionality.
– For each image, add a handler to its event 'onclick'.
• If it is a get-up image, add a 'get up' event
• If not, then add a 'get down' event.
– Implement both previous events: 'get up' and 'get
down'.
• 'get up' event will move the list item to the next, if
exists.
• 'get down' event will put the clicked list item before
its previous, if exists.