Listeners make an HTML element stand at the ready, waiting to do what it has been tasked with.
Once familiar with the built-in JavaScript and additional MooTool events that we can bind actions to, we note the addEvent()
syntax from the previous recipe and move on to the more agile addEvents()
syntax.
The syntax for adding multiple events is similar enough to adding a single event that one could nearly guess it. Look at this example to see how intuitive it is:
<script type="text/javascript" src="mootools-1.3.0.js"></script> </head> <body> <div id="my_trigger" style="width:100px; height:100px; border:1px solid #BEBEBE; line-height:100px; text-align:center;"></div> <script type="text/javascript"> $('my_trigger').addEvents({ 'mouseover': function() { this.set('html','MouseOver!'); }, 'mouseout': function() { this.set('html','MouseOut!'); }, 'click': function() { var width = (this.getStyle('border-width'). toInt()==1) ? '5px' : '1px'; this.setStyle('border-width',width); } }); </script>
The syntax for adding multiple events is very similar to that of adding a single event. Remembering that addEvent()
takes the event name and the function to execute, we can easily see that addEvents()
takes the same two arguments, only in hashed form so that multiple event names can have individual functions applied to them.
In our example, we have defined three events to listen for: onmouseover, onmouseout
, and onclick
. Remove the "on" prefix for events when using these functions.
Note
MooTools adds two important events that help to solve the event bubbling dilemma where each parent and children both report events causing them to fire more times than one would expect: mouseenter
and mouseleave
. These events were originally proprietary to Internet Explorer.
New to what we have seen so far in the book is Element.setStyle().
This method, along with its sibling, Element.getStyle()
, do just as they suggest. They help us to get and set style properties. The syntax parallels that of addEvent()
and addEvents()
.
Our goal for this chapter is to sit down and remove a lot of cut-and-paste code from one of our projects and replace with a very slick, object oriented roll over based on this recipe. Let's go!