Here we will learn how to use an event listener to pop up an alert box.
We are familiar with how to place an HTML attribute like onmouseover
that will execute upon a user's mouse entering the space of the HTML element. This is a frequent method of creating roll-over actions for buttons on website navigation. When editing a website that has these code-heavy roll overs, it can be confusing how to alter the roll overs. They create quite a bit of code.
Now MooTools makes our lives easy; we see that MooTools itself is becoming an oldie-and-goodie. It is exciting to learn that using listeners, heretofore a jUnGlE
of confusing syntax, is now as simple as calling the addEvent()
method with which MooTools has extended our elements.
<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:50px; text-align:center;">Click Me</div> <script type="text/javascript"> var count = 0; $('my_trigger').addEvent('click',function() { $('my_trigger').set('html','Click Me<br/>'+(++count)); alert('Hello, please be aware that my_trigger has been clicked!'); }); </script>
The addEvent()
method takes two arguments (1) the event name and (2) the callback handler or function definition. Event names include all the common events defined by HTML; however, they each drop the "on"; for instance, instead of passing "onSubmit" as the event name, pass "submit": $('my_form').addEvent('submit',function() { return false; })
;.
The World Wide Web Consortium, W3C, publishes a plethora of information on events in HTML. While we might not have time to read all of it, being familiar with where it is allows us to seek out the answers to really advanced questions that will come up along the path of our development careers.
In our example, we add an event function to my_form
. Within that function we then make calls to the same element my_form
. This can be reduced further by using a keyword that describes the element that is the owner of the executing function, this:
$('my_trigger').addEvent('click',function() { this.set('html','Click Me<br/>'+(++count)); ...