Join the DZone community and get the full member experience.Join For Free
Bugsnag monitors application stability, so you can make data-driven decisions on whether you should be building new features, or fixing bugs. Learn more.
Both examples are common ways of including client-site scripting to take place when users interact with links or buttons. And both ways have a better alternative.
- Maintenance: If you change the name of the function, or the parameters, you would need to update every single call to the function. Which sucks if you have a lot of buttons.
Adding Events with Mootools
First of all, it’s very easy to add Event Listeners to DOM objects with Mootools. You just access the DOM Element, and use the
addEvent() function. Here’s how:
<a href="dostuff.html" id="button">Do Stuff</a>
This gets the DOM Element of ID button. The function
addEvent() takes 2 parameters, the first being the type of Event, click in this case, and the second being a function to execute when that Event is heard.
.bind() and .each()
Here’s two extra functions that are very useful to know when adding Event Listeners to Elements.
.each() helps make adding this function page wide extremely simple. Let’s take a look.
<a href="dostuff.html" class=”butto>Do Stuff</a>
$$('.className') we’ve grab an array of DOM Elements, all with the class of button. Then, using Mootools’
Array.each() function, we iterate over every object in the Array, and access it using the parameter we pass, in this case stuffButton.
Also useful, is if you use the
addEvent() function in a class and want call a different class function, you’ll find
this.classFunction() to betray you. This is because
addEvent() is a function of Element, so using
this inside that function will think it refers to the instance of that Element, instead of the class you had hoped.
To leverage the
this keyword back into your control, you’ll use the
You can use any object as the parameter of
bind(), making that object accessible with
Events to Mootoolize
addEvent. Simple remove the ‘on’ and keep the rest of the word.
- onMouseOver - Useful rarely. Usually, CSS psuedo-class
:hoveris the proper use.
- onKeyPress - I think. If it’s not a useable inline, at least
keypressis an Event you can listen for.
Opinions expressed by DZone contributors are their own.