This blog has moved here: woorkup.com | FOLLOW ME ON TWITTER @woork
Thursday, August 21, 2008

MooTools Basic Tips for Web Designer (Lesson 1)

After a lot of requests, in this article I want to illustrate some simple tips to start to work with MooTools. In this first lesson you can see how to manipulate element properties, in particular how to get DOM element by ID, how to use getStyle(), setStyle() (to get and set CSS properties), toInt() to convert string to number and some examples to introduce how to write unobtrusive JavaScript code with MooTools.


1. Add Mootols framework to your page
First, you have to download the latest version of MooTools and add a link to the framework within the <head> tag of the page:




Copy and paste the following code within the <head> tag:

<script type="text/javascript" src="mootools.svn.js"></script>

Ok, now you are ready to use MooTools feautures in your web pages!


2. Get DOM element
To get a DOM element by ID you can use the following syntax:

var element = $('myElement');

... this line of code gets the element with ID="myElement" in your page. If you have some falimiarity with JavaScript, it's almost the same thing to get a DOM element by reference using the following code:

var element = document.getElementById('myElement');

Ok, now using $$ you can get an array of elements within a DOM element with a specific ID:

$$('#myElement li.myListElement');

...for example, this line if code returns an array of all <li> tags with the class="myListElement" within the DOM element with ID="myElement".


3. setStyle() and get Style()
These are two basic methods to set and get element properties (height, background, color...). To set a property you can use the following code:

$("myElement").setStyle("height", "200px")

...or if you have to set multiple properties you have to use the following code:

$("myElement").setStyles({
background: "#DEDEDE",
border:"solid 1px #999999",
width: "700px"
height: "80px"
});

To get a property you can use getStyle() specifying the property you want to get (height, background, color...):

$("myElement").getStyle("height")

The previous code returns the height of the DOM element with ID="myElement", for example "200px". If you want the number (200 and not the string "200px") you have to use the following code:

$("myElement").getStyle("height").toInt()

...in this way the value returned will be a number (200).


4. Unobtrusive Javascript
Now, we can start to see how to write unobtrusive Javascript code using MooTools in order to separate page content from JavaScript code. Your have to use the following code:

<script type="text/javascript">
window.addEvent('domready', function() {
//Some lines of code here...
});
</script>

For example I want to write a simple script which display an alert with "Hello World!" when an user click on a link with ID="myElement". The script is:

<script type="text/javascript">
window.addEvent('domready', function() {
$('myElement').addEvent('click', function() {
alert('Hello World!');
});
});
</script>

...and HTML code is:

<a href="home.html" id="myElement">
Try to click here!
</a>

...instead of an "obtrusive" code with onClick event which calls a function (for example doSomething()) added within the <a> tag:

<a href="home.html" id="myElement" onClick="javascript:doSomething()" >
Try to click here!</a>


Example 1: change background color
Ok, now we can try to write a simple code which change the background color of a layer with ID="myLayer":



HTML code is something like this:

<div id="myLayer">
<a href="#" id="myElement">Change Background</a>
</div>

...how you can see, you don't call a JavaScript function using an event (onClick, onFocus...) within <a> tag. The reference to the DOM element "myLayer" will be insert into the following script which you have to add below the link to the MooTools framework in the <head> tag (step 1):

<script type="text/javascript">
window.addEvent('domready', function() {
$('myElement').addEvent('click', function() {
$('myLayer').setStyle('background', '#DEDEDE');
});
});
</script>


Example 2: change and reset background color
Now we can modify the previous code and make it a little bit more complex. In this example when an user clicks on "Change Background", if the background colors of the layer with ID="myLayer" is not set, then the script sets the background color of the layer to this value "#DEDEDE"; else, the script set the background color to null.




HTML code is the same of the previous example:

<div id="myLayer">
<a href="#" id="myElement">Change Background</a>
</div>

... but I changed something in the script:

<script type="text/javascript">
window.addEvent('domready', function() {
$('myElement').addEvent('click', function() {
var currentBgColor = $('myLayer').getStyle('background');
if(currentBgColor==''){
$('myLayer').setStyle('background', '#DEDEDE');
} else {
$('myLayer').setStyle('background', '#FFFFFF');
}
});
});
</script>


Download source code


How you can see the code is very simple. Now you can start to write more complex functions to manipulate element properties. In the next lesson we we'll see how to interact with Forms using MooTools.

Do you have some suggest? Add a comment!

blog comments powered by Disqus
Ninja said...

Hi there! Thanks for this post :) Great resource!

AK said...

Hot stuff! Will get cracking at some MooTools features.

Thanks, I've always appreciated your woork! ;)

Sean McArthur said...

Good for those starting in Mootools. Especially teaching to remove Javascript from inline HTML elements and containing them in Javascript files. There's a link to an article about doing just that, as well as some additional tips to make things nicer, like using event.stop(), .bind(), and $$().each().

Anonymous said...

rather than having a local copy of mootools on the server why not use the google hosted version?

http://code.google.com/apis/ajaxlibs/documentation/#mootools

MO BETTA

Anonymous said...

This may be a stupid question, but I'm using your slide panel with mootools and it interferes with another javascript I have set up for my navigation. Is there a simple way around this? thanks

Matthew said...

Great resource! Thank you for the informative post, I look forward to using MooTools in future projects along side with this post :).

Personal Trainer said...

I like MooTools, but so far I've written quite a bit using the Scriptaculous/Prototype frameworks... They collide. jQuery offers a noConflict option which relinquishes the $ to the other framework...

Gerasimo said...

I'm a jQuery fan but it's always good to know your alternatives. Great article. Thanx for that :)

Aidi said...

Usefull article, Thanks.
But I think in the Example 2 the back ground will back to white only once (after the second click)
but the following clicks will keep the dark bg color.
Isn't that?
should add a condition the if statement to check for #FFFFFF color :)

Jeremie said...

Great article!

Prime 31 wrote some nice lessons as well: MooTools 1.2 for The Non Programmer

Michael Kaiser said...

I ever wanted to integrate MooTools into my Serentipity Weblog. I tried a hundred times and I tried again after your really easy article.
Your Demo works perfectly, but it fails if I include it in my Blog. I deactivated Lightbox (based on prototype) and deleted every other JavaScript, but it still does not work.
I ever get the JavaScript Error "TypeError: Value undefined does not allow function calls."
Who can tell me what's wrong?

Michael Kaiser said...

I don't believe it: after trashing my downloaded mootools.js and replacing it with your mootools.svn.js from the demo it suddenly works!
Perhaps that's because you are using version 1.11 and I downloaded the actual version 1.20.
Crazy stuff, bad update…

Jamie Lottering said...

Nice to see a MooTools lesson for a change

Prasath said...

Thank you very much this helped me so much
ps: Love your blogger theme
How did you do it ?

Anonymous said...

works great! thanks!!!
is awesome!!!

Alessandro said...

Ciao, volevo ringraziarti per l'utilissima e semplice guida sul Mootools. Volevo chiederti come posso fare a selezionare attraverso Javascript tutti gli oggetti aventi una stessa classe (e non ID come nel caso del tuo esempio) in una pagina.

Ivan - from Brazil said...

Best intro i´ve ever read.
Finaly i´ve learned something about this (now i can see) amazing mootols.

Very thanks.

Now you are on my favorites!

Web Designer said...

Moo Tools are pretty cool. I have to try it out.

Daniel said...

Thanks man. Your tutorials are great. Nice looking site and great content as well, thats pretty rare. Keep up all the good work.

jhon said...

Great article,I'm using your slide panel with mootools and it interferes with another javascript I have set up for my navigation.Moo Tools are pretty cool.

http://www.cyberdesignz.com/

Suparna said...

Thank you so much for sharing these nice tips. This is the first time i hear about Moo Tool and have decided to use this on my next project.

car57 said...

okay I am a designer with very elemental understanding of scripting. I am using a mootools-based lightbox, milkbox, and need to figure out how to write a function that tests if browser is Firefox Mac 2, then change the overlayOpacity to 1 and give mbOverlay a background grey png (to work around a Gecko rendering issue with swfs and opacity). milkbox.js is where the overlayOpacity is set.

How do I write this function, and where do I put the code--in the head of the html where the lightbox is? Assume I have to do the domready event?

Thanks so much in advance!

web design said...

Nice post. thanks for the info.

Go-Gulf said...

Good for those starting in Mootools. Especially teaching to remove Javascript from inline HTML elements and containing them in Javascript files. There's a link to an article about doing just that, as well as some additional tips to make things nicer, like using event.stop(), .bind(), and $$().each().

Know Rather than having a local copy of mootools on the server why not use the google hosted version?

somnath said...

Good Woork !!!

Victoria said...

Thanks for the step by step guide!

  • Twitter Follow woork on Twitter
  • RSS Feed Subscribe to stay up to date
  • Podcast Coming soon...
  • 0 delicious lovers save
Share your links. Do you want to suggest any interesting link about web design or tech news? Submit your link.
Submit a News