Wednesday, April 13, 2011

[TUT] A Beginner's Guide to Mootools


A Beginner's Guide to Mootools

By: Matt Vicker

Getting started with any type of framework can be an intimidating experience. To help, this week we have an in depth tutorial and long screencast to provide a crash-course for this popular JavaScript library. With so much focus on jQuery, it's easy to forget that Mootools is an equally powerful library with a huge following.




After the initial move to Mootools I was frustrated with the lack of community support and ended up moving back to Prototype immediately. After I was more comfortable with working with frameworks I moved back to Mootools and haven't looked back.

With this tutorial, I'm going to try to make sure that you have a great beginning to the Mootools framework. I'm going to walk you through getting everything downloaded and setup as well as some of the basic elements of Mootools. After that I'm going to spend some time walking you through how to use the Mootools Docs, which is a site that you'll be visiting very often during the use of Mootools.

All right, enough stories, lets get our hands dirty.

Some Requirements


The nice thing about working purely with javascript is we don't need to run the files on a web or local server. All you need for this tutorial is:
A text editor/IDE
A browser
Some time.


For this tutorial I will be using Firefox and Firebug to show you some debugging tips, so I recommend that you use firefox as well as Firebug. Firebug will make working with Mootools, or any framework, 100x easier.


You can download firebug here

Downloading the Framework




Head over to www.Mootools.net/download


For now we are going to include both the Core and More libraries. This is just to make sure we aren't missing anything. When you become more comfortable with Mootools you will realize that not all the components are needed for specific applications, so you can custom build Mootools libraries to fit your need and keep the file sizes small.

Download the Mootools 1.2.3 YUI compressed file and save it to your desktop.




Move over to the more builder, select every option and download the YUI compressed file.

Setting up the Framework


Let's create a new folder called Moo and inside that folder lets create another folder called inc. Just to make things easier, create one more file inside our inc folder called js and toss both Mootools files inside that folder.

Inside our Moo folder, create a new file called index.html and open that sucker up.




Is it open? Good, now open it in Firefox as well. You should see a blank page. Switch back to your index.html file in your editor.

To include Mootools into our script, we need to add 2 lines of code to your HTML file. If you've ever included a javascript file into a script before this will be very familiar to you.


<script type="text/javascript" src="inc/js/Mootools-1.2.3-core-yc.js"></script>
  <script type="text/javascript" src="inc/js/Mootools-1.2.3.1-more.js"></script>
We are now setup and ready to go!

Making Mootools talk to elements


To get Mootools to talk to elements on our page we use the $() function to get an element by it's ID.

Let's create a new div, give it an ID and some text and then make Mootools talk to it.


<div id="box"><p>Hey Guys!</p></div>

  After that lets put some javascript tags so we can start writing some Mootools.

  <script type="text/javascript">

   //I hold the javascript

  </script>
We've created out div and gave it an ID of "box". We inserted some text inside of it and created some script tags so we can start entering in some Mootools goodness.
If we use the $ function and pass the id of our box, we can see that Mootools is not getting all the attributes of our "box" div. Our variable element now holds all that data.


var element = $('box');

If we refresh the page, we can't visibly see that anything is happening, but we know things are going on in the background. This is where console.log() and Firebug come into play.

If you open up Firebug, you should see a blank console. Using console.log() we can pass information to Firebug to display for us. This is extremely useful when debugging a script because you can use it to display information in various steps of your script to see where things are failing.

                      console.log('Oh, Hi Everyone!');





We can also use it to display information that otherwise wouldn't be displayed in our browser.

Lets use console.log() to display some information about our "box" div.


console.log(element);








So we've learned that we can use $() to get an element but what if we want to get the information of many elements. We don't want to use 100 instances of $() that will just get messy. This is where the $() comes into play!

Who needs to get one, lets get many!

Lets add 5 links to our page.


<p><a href="http://linkone.com">I'm the first link</a></p>
  <p><a href="http://linktwo.com">I'm the second link</a></p>
  <p><a href="http://linkthree.com">I'm the third link</a></p>
  <p><a href="http://linkfour.com">I'm the fourth link</a></p>
  <p><a href="http://linkfive.com">I'm the fifth link</a></p>

  ...
  javascript tags
  ...

  var links = $$('a');

  console.log(links);

Our links variable now holds an array of all our links.






All right, so we've created our elements and now we've got Mootools talking to them, but this isn't any fun. The front end user isn't seeing any changes, so lets move away from this boring backend stuff and move onto something a little more fun!

Getters and Setters


We've just covered getting the elements using our getter functions. We can get a single element using $() and the elements ID. We've also covered getting multiple elements using $() and the element type.

When using $() we can either pass the HTML tag name or use CSS class selectors to grab group of elements. A quick example of grabbing class names would look like this.


var elements = $$('.myclass');

That would return an array of all elements on the page with the css class of "myclass".

Theory is dry as a bone and that's what the docs are for but you came here to get your hands dirty, so lets get dirty.

Now that we are getting our elements, lets use the setter functions to manipulate the elements on screen.

Our "box" div is looking kinda plain so lets add some color to it. We've already set our element into our element variable.


element.set('styles',{
   'color':'red'
  });

We use our element variable and we attach the set() function by using element.set().

There are many arguments we can use to change our element, but for now we are going to use styles. Next we pass some options to our styles argument. We are passing the color option and setting our text to red. Styles can use all available css options. Let's change the background color while we are here. Feel free to play around with the styles and see how colorful you can make our box element.


element.set('styles',{
   'color':'red',
   'background':'yellow'
  });

Our "box" element is not looking a little less plain. If we wanted to apply many styles to our box element it could end up being a lot of unnecessary code. Luckily, we can use CSS styles and another set argument to cut down on out code. Go ahead and delete out element.set() code. We are going to add some css styles using inline css.


Note: To make things easier we are going to write our CSS inside the file, but when creating an actual website it is good practice to have all your CSS and Javascript in separate file.

Above your "box" div lets add some style tags and create a class of .myclass.

We can now use set('style') to add our new style to our element.


element.set('class','myclass');










A few other argument we can use with set are HTML and text. Some basic examples of this are:


element.set('html','<p><b>Hey Guys, now I am bold</b></p>');
  element.set('text','Hey guys, no html here');

Which argument you use will depend on what you need to use it for. If you do not need to pass HTML values, you'd use text and vise-versa if you needed to pass HTML values.

We've used set() to add some styles to our "box" div, but we could've just added the class to the div using HTML. We don't really need to use Mootools to add the style if we are just changing it before the user even sees the change. This is where events come in handy.

We are hosting an event and everyone is invited!


Lets go ahead and delete all those links we created and clear our javascript tags.

Your index.html file should now include only this code:


<style type="text/css">

   .myclass{
    font-family: Helvetica;
    font-size: 1.4em;
    color: red;
    background: #e1e1e1;
    border-bottom: 2px solid #999;
    padding: 4px 0 0 15px;
    margin: 0;
   }

  </style>

  <div id="box"><p>Hey Guys!</p></div>

  <script type="text/javascript">

   var element = $('box');

  </script>




Create a new link and give it an ID of button right under out "box" div.


<p><a href="" id="button">Click me please!</a></p>

Now we are going to add an event to this button so we can execute some code when a user clicks the link. We use addEvent() to do this.


$('button').addEvent('click',function(e){

  });
We are using the familiar $() function to tell Mootools we want to talk to the link with an ID of button. Next we attach the addEvent() and pass 2 arguments. The first argument is the event that we want to capture which is when a user clicks the link. The second argument is a function with a variable of e. This function is going to execute when the user clicks the link and the variable of e passes the event. You'll understand why we pass a variable with the function in this next step.


...
  inside addEvent
  ...

  e.stop();


We assign the stop() function to our variable of e to stop the browser for send the link action. Usually when you click the link, the page will refresh and all your changes will be lost. e.stop() stops the browser from refreshing the page so we can do some Mootools magic!


Now we have Mootools capture the click event so lets make Mootools add our class of .myclass to our "box" div when the link is clicked.


...
  inside addEvent()
  ...

  element.set('class','myclass');


Save this, refresh the page and click your link. On clicking the link, the div should now have some styling to it. We did all that without having to refresh the page. This is where Mootools starts to get very interesting.


Quick little refresher before we continue. We've learned how to use getter functions ($ and $) to allow Mootools to talk to elements on our page. Then we learned that we could use setter functions to manipulate those elements. Events allow use to capture user interaction so that we can manipulate elements in realtime without having to refresh the page to reflect each change.

Creating elements are a snap!



Mootools will also allow you to create new elements on the fly so we can let the user customize the page. To do this we are going to be using the new Element() and inject() functions.


Lets start with a fresh HTML file. Either delete everything from index.html or create a new file.


In our file we are going to create a div and 2 links. Go ahead and create those now!


<div id="result">

  </div>

  <p><a href="" id="grey_box">Add a Grey Box</a></p>
  <p><a href="" id="blue_box">Add a Blue Box</a></p>

  <script type="text/javascript">


  </script>

We are going to use the $() to add an event to both of our links on the page. We are going to capture the click event and then create a new element. Lastly we are going to inject our new element into our "result" div.


$$('a').addEvent('click',function(e){

   e.stop();

  });

We use $('a') to grab all the links and then attach the addEvent() to each link. We do this because it cuts down on coding so we don't have to find each ID of the links and create addEvents for them. We are going to use the ID of each link to determine which style we need to add. Lets whip up some quick css for the boxes we are going to create.


<style type="text/css">

   .grey_box{
    height: 50px;
    width: 50px;
    float: left;
    clear: none;
    background: grey;
   }

   .blue_box{
    height: 50px;
    width: 50px;
    float: left;
    clear: none;
    background: blue;
   }

  </style>


Now it's time to create our elements and inject them into the page.


var class = this.id;

  var box = new Element('div',{'class':class});

  box.inject($('result'));


First we are creating a variable called "class" the hold the ID of the link that was clicked. Our next line takes care of creating the element. We do this by using new Element() and then passing some arguments. The first argument is the type of element we want to create. We want to create a div, so we pass a value of div. The second set is our options. We want to assign a different class depending on which link was clicked. We do this by first telling the function that we want to set the "class" option, then we pass our variable of class which will return either"blue_box" or "grey_box".

The last line is taking our new element, which we placed into a "box" variable and is injecting it into our "result" div. Mootools knows to inject it into "result" because we are passing the"result" div using a getter method as the main option.

Now if we refresh the page and start clicking our links you should see that little boxes are being created on the fly and are being added to the page.

I have that effect on people


At this point in the tutorial you should be fairly comfortable with using getter and setter functions to get Mootools to talk to our elements.

For the last part of this tutorial I'm going to touch on some of the animation and effects functions that Mootools offers.

Lets create another new file. Inside that file create a div with some text inside of it and a link.


<div id="box">
   <p>Hey Guys!</p>
  </div>

  <p><a href="" id="button">Click Me</a></p>

  <script type="text/javascript">


  </script>


I've added ID's to each element so we can get Mootools talking to them.


To start, lets attach an event to the link. This should look very familiar by now.


$('button').addEvent('click',function(e){

   e.stop();

  });
 
Now that we have Mootools capturing the click event, lets make our "box" div fade in and out on each click.


$('box').fade('toggle');

Now, when we click our link the box div should fade away. If we click the link again it will reappear.


Fading is cool and all, but lets add some style to the box and see if we can make it grow!


<style type="text/css">

   #box{
    width: 100px;
    background: yellow;
   }
 
</style>

We are going to use the tween() function to animate some attributes of our "box" div.
Inside our click event lets remove out fade() function and replace it with tween().


//$('box').fade('toggle');
  $('box').tween('height', '200');

Now if we click the link, our box should grow taller.
The tween function takes 2 arguments. The first is the attribute we want to manipulate and the second is a value. We want to change the height of the box and we want it to animate to 200px.
What if we wanted the box to grow by 10px every time we clicked the link. First we would have to get the current height of the box. I think we can do that with our $() getter function.


var box = $('box');
  var height = box.getHeight();
  var new_height = height + 10;

  box.tween('height', new_height);

First we assign our "box" div to a variable of box. Next we use a built in function of Mootools called getHeight() to get the current height of our "box" div. We want the box to grow by 10px each time the link is clicked so we create a new variable called new_height and assign it a value of height + 10. This is taking the current height and increasing it by 10. Finally we attach the tween() function to our box variable, tell it we want to animate the height and pass it the value of new_height.


If you click the link, the box should grow. If you click it again it will continue to grow with each mouse click.

We should document this!






Mootools has an extensive document section on their website. http://Mootools.net/docs/core

If you plan on using Mootools you will become very familiar with this section of their site. It is broken up into the different available classes and functions that Mootools has to offer.

The section that you will be visiting the most will be the Element section. This is the section that has all the information on how Mootools communicates and manipulates the elements on the page.

I've given your broad strokes to help you get used to how Mootools functions and if you would like to continue learning I suggest you read over a few of the pages in the Mootools docs.

Link download source code :

http://www.mediafire.com/file/dz5sk66dh47ybqw/wdeveloper.blogspot.com_beginners_guide_to_mootools.zip

No comments:

Post a Comment