DOM Events

You have probably used something like onclick or onblur before. Those are events. (Check out the W3School Event Reference.) MooTools makes events very simple to use. Whether that means adding, removing or even making your own events! Did you know you already know the basic syntax for adding events? (Guess when you learned that.) ;-)

$('header').addEvent('click', function(e){
 $('header').setStyle('border','1px solid white');
  alert('You clicked me!');
});

It's almost the same as DomReady! This time though, we're focused on the addEvent part.

Discussion

  • addEvent is 100% non-intrusive to HTML. (Meaning that you don't have those pesky onclick=“func()”)
  • Not inline at all. JavaScript is separated from markup.
  • Allows you to add more then just one function to any element for the same event.
  • You can stop the Event by returning false in the listener or calling stop on the argument passed in.
  • This method is also attached to Document and Window.
  • MooTools addEvent is similar to Prototype's observe and jQuery's bind.

What Not To Do

<a href="#" onclick="myAjaxFunction(); return false;">When you click me, I'll do some Ajax magic :D</a>

With MooTools addEvent, you no longer need to use inline events. In fact, you should no longer do this. MooTools can even handle the return false part. As long as you understand that inline event handlers are off limits, you're set.

addEvent Syntax

/*
 addEvent Syntax - Since you already know...
*/
 
$('header').addEvent('click', function(){
 $('header').setStyle('border','1px solid white');
  alert('You clicked me!');
});

You can test out yourself by simply making an a tag with an id and wraping the code above in DomReady and making the appropriate changes.

Notes

You might hear the three E's of Javascript every now and then. Those would be Elements, Events and Effects. We've covered events.

Continue to Stopping DOM Events

 
walkthrough-1.2/dom-events.txt · Last modified: 2009/03/24 14:06 by night815
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki