We can attach event listeners to elements on a web page using the addEvent
and addEvents
methods. By doing so, we're able to find out whenever that event happens, as well as execute a function to react to them.
Adding event listeners is the basis for interactivity, and is where JavaScript and (subsequently) MooTools has gained its popularity. Imagine being able to perform an operation whenever a user hovers over an image, or clicks on a link, or whenever the user submits a form; the possibilities are endless.
The addEvent
method allows you to add one event listener to an element method, and follows the format:
$(yourelement).addEvent(event, function(){})
For example, in the following code block, we attach a click event listener for all<a>
elements. When the user clicks on any hyperlink on our web page, it runs a function that opens up an alert dialog box that says, You clicked on a hyperlink.
$$('a').addEvent('click', function(){...