Working with Events in MooTools: Part 2

Exclusive offer: get 50% off this eBook here
MooTools 1.2 Beginner's Guide

MooTools 1.2 Beginner's Guide — Save 50%

Learn how to create dynamic, interactive, and responsive cross-browser web applications using this popular JavaScript framework

$23.99    $12.00
by Jacob Gube | December 2009 | Java Open Source

Read Part One of Working with Events in MooTools here.

Removing, Cloning, and Firing off Events

Besides adding event listeners, other operations you may want to do are removing events from an element, cloning events from other elements, and firing off events for elements manually. We'll go through each one of these operations.

Removing events from elements

There are instances when you want to remove an event listener that you've added to an element. One reason would be that you only want to an element to be triggered once, and after that event has been triggered, you no longer want to trigger it again. To ensure it only fires once, you should remove the event once certain conditions have been met.

Removing a single event from elements

There are two methods available to you for removing events from elements. The first is removeEvent() which removes a single specified event.

Time for action – removing an event

Let's say you have some hyperlinks on a page, that when clicked, will alert the user that they have clicked a hyperlink, but you only wanted to do it once. To ensure that the warning message appears only once, we'll have to remove the event after it has been fired.

This type of thing may be utilized for instructional tips: when the user sees an unfamiliar interface element, you can display a help tip for them, but only once - because you don't want the tip to keep showing up every single time they perform an action.

  1. First, let's put some links on a web page.
    <a href="#">Hyperlink 1</a> <a href="#">Hyperlink 2</a>
  2. Next, let's create a function object that we will call whenever a click event happens on any of the links on our page. When the function fires, it will open up an alert box with a message, and then it will remove the click event  from all <a> elements on the web page.

    // Create an function object
    var warning = function() {
    alert('You have clicked a link. This is your only warning');
    // After warning has executed, remove it
    $$('a').removeEvent('click', warning);
    };
  3. Now we add a click event listener that will fire off the warning function object.

    // Add a click event listener which when triggered, executes the
    //warning function
    $$('a').addEvent('click', warning);
  4. Our script should look like the following

    window.addEvent('domready', function(){
    // Create an function object that will be executed when a
    //click happens
    var warning = function() {
    alert('You have clicked a link. This is your only warning');
    // After warning has executed, remove it from all <a>
    //elements on the web page
    $$('a').removeEvent('click', warning);
    };

    // Add a click event listener which when triggered, executes the
    //warning function
    $$('a').addEvent('click', warning);
    });
  5. Test in your web browser by clicking on any of the hyperlinks on the page. The first time you click, you'll see an alert dialog box with our message. The second (or third, forth, fifth… you get the picture) time you click on any hyperlink, the alert dialog box will no longer show up.

    MooTools 1.2 Beginner's Guide

Removing a type of event, or all events, from elements

If you want to remove a type of event on an element (or set of elements), or if you want to remove all events regardless of its type from an element, you have to use the removeEvents method.

To remove a type of event from an element, you pass the type of event you want to remove as a parameter of the removeEvents method. For example, if you wanted to remove all click events that were added using MooTools addEvent method from an element called myElement, you would do the following:


$('myElement').removeEvents('click');

If instead, you wanted to remove all events that myElement has regardless of the type of event it has, then you would simply run removeEvents as follows:


$('myElement').removeEvents();

Cloning events from another element

What if you wanted to copy all event listeners from another element. This could be useful in situations where you clone an element using the clone MooTools element method. Cloning an element doesn't copy the event listeners attached to it, so you also have to run the cloneEvents method on the element being cloned if you wanted to also port the event listeners to the copy.

To clone the events of an element, follow the format:

// clone the element
var original = $(‘originalElement’);
var myClone = original.clone();

// clone the events from the original
myClone.cloneEvents(original);

Firing off Events

Sometimes you want to fire off events manually. This is helpful in many situations, such as manually firing off an event listener functions that is triggered by another event. For example, to fire off a click event on myElement without having the user actually clicking on myElement, you would do the following:

$('myElement').fireEvent('click');

Time for action – firing off a click event

Imagine that you have a hyperlink with a click event listener attached to it, that when triggered, alerts the user with a message. But you also want to fire off this alert message when the user presses the Ctrl key. Here's how you'd do this:

  1. First, let us place a hyperlink in an HTML document. We'll put it inside a <p> element and tell the users that clicking on the hyperlink or pressing the Ctrl key will open up an alert dialog box.

    <body>
    <p>Show a warning by clicking on this link: <a href="#">Click
    me</a>. Alternatively, you can show the warning by pressing the
    <strong>Ctrl</strong> key on your keyboard.</p>
    </body>
  2. Next, let's add an event to <a> elements. We'll use the addEvent method to do this.

    // Add a click event
    $$('a').addEvent('click', function(){
    alert('You either clicked a link or pressed the Ctrl key.');
    });
  3. Now we have to add another event listener onto our HTML document that watches out for a keydown event. The function that the event listener executes will check if the key pressed is the Ctrl key by using the control Event method which returns a Boolean value of true if the Ctrl key is pressed.

    If the key that was pressed is the Ctrl key, we ask it to fire the click event function that we set in all our a elements by using the fireEvent method with click as its parameter.


    // Add a keydown event on our web page
    window.addEvent('keydown', function(e){
    // If the keypress is the Ctrl key
    // manually fire off the click event
    if(e.control) {
    $$('a').fireEvent('click');
    }
    });
  4. All together, our MooTools script should look like this:
    window.addEvent('domready', function(){
    // Add a click event
    $$('a').addEvent('click', function(){
    alert('You either clicked a link or pressed the Ctrl key.');
    });
    // Add a keydown event on our web page
    window.addEvent('keydown', function(e){
    // If the keypress is the Ctrl key
    // manually fire off the click event
    if(e.control) {
    $$('a').fireEvent('click');
    }
    });
    });
  5. Test your HTML document in the web browser. Click on the “Click me” link. It should show you the alert message we created. Press the Ctrl key as well. It should also open up the same alert message we created.

    MooTools 1.2 Beginner's Guide

The MooTools Event Object

The MooTools Event object, which is part of the Native component, is what allows us to create and work with events. It's therefore worth it to take a bit of time to explore the Events object.

Using Event Object Methods

There are three Event methods: preventDefault, stopPropagation, stop.

Preventing the default behavior

Events usually has a default behavior; that is, it has a predefined reaction in the instance that the event is triggered. For example, clicking on a hyperlink will direct you to the URL that href property is assigned to. Clicking on a submit input field will submit the form to the value that the action property of the form element is assigned to.

Perhaps you want to open the page in a new window, but instead of using the non-standard target property on an <a> element, you can use JavaScript to open the page in a new window. Or maybe you need to validate a form before submitting it. You will want to prevent the default behaviors of an event doing either one of these things. You can use the preventDefault method to do so.

Time for action – preventing the default behavior of a hyperlink

Imagine that you have a list of hyperlinks that go to popular sites. The thing is, you don't want your website visitors to ever get to see them (at least coming from your site). You can prevent the default behavior of your hyperlinks using the preventDefault method.

  1. Here is the HTML markup for a list of <a> elements that go to popular websites. Place it inside an HTML document.

    <h1>A list of links you can't go to.</h1>
    <ul>
    <li><a href="http://www.google.com/">Google</a></li>
    <li><a href="http://www.yahoo.com/">Yahoo!</a></li>
    <li><a href="http://digg.com/">Digg</a></li>
    </ul>
  2. We will warn the user with an alert dialog box that tells them they can't access the links, even when they click on it. We'll fire this alert dialog box when a user clicks on it. Notice the e argument in the function? That is the event object that is passed into the function, allowing us to access events' methods and properties.
    $$('a').addEvent('click', function(e){
    alert('Sorry you can't go there. At least not from this page.');
    });
  3. Open your HTML document in a web browser and verify that the links still open their destination, since we haven't prevented the default yet. You will, however, see the alert dialog box we set up in step 2, showing you that, indeed, the click event listener function fires off.
  4. Now we will prevent the links from opening by using the preventDefault method. We'll just add the following line above the alert(); line:
    e.preventDefault();
  5. Test the document again in your web browser. Clicking on any hyperlink opens the alert dialog box, but doesn't open the hyperlink.

    MooTools 1.2 Beginner's Guide

Preventing event bubbling

Event bubbling occurs when you have an element inside another element. When an event is triggered from the child element, the same event is triggered for the parent element, with the child element taking precedence by being triggered first.

You can prevent event bubbling using the stopPropagation method. Let's explore the concept of event bubbling and how to prevent it from occurring (if you want to), using the stopPropagation event method.

MooTools 1.2 Beginner's Guide Learn how to create dynamic, interactive, and responsive cross-browser web applications using this popular JavaScript framework
Published: December 2009
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Time for action – preventing event bubbling

Let's say you have two divs, one inside another. When a div is clicked, it will open up the alert box that displays the div's ID property value.

  1. Let's start with the HTML. In the following HTML markup, we have two div elements. The parent div has an ID of #parent and the child div has an ID of #child.
    <body>
    <div id="parent">
    <p>#parent</p>
    <div id="child">
    <p>#child</p>
    </div>
    </div>
    </body>
  2. We'll style them with different background colors, widths, and heights so we can see each div better.
    #parent {
    width:200px;
    height:200px;
    background-color: #999;
    }
    #child {
    width:100px;
    height:100px;
    background-color:#ccc;
    }
  3. Open the HTML browser. You should see the following:

    MooTools 1.2 Beginner's Guide

  4. Let's explore the concept of event bubbling by adding a click event on all divs in the web page. When the click event is triggered, we will display an alert dialog box with the ID of the div that triggered the event.

    $$('div').addEvent('click', function(e){
    alert('You clicked on #' + this.get('id'));
    });
  5. Open or refresh your work in your web browser. Click on the #parent div. You should see one alert dialog box that displays the ID of the parent div.

    MooTools 1.2 Beginner's Guide

  6. This step is where you'll see event bubbling in action. Click on the #child div. You should see two alert boxes, one right after the other. The first one will display an alert that you clicked on #child div, and the second one will alert you that you clicked on #parent div, effectively running the same function twice in one click.

    MooTools 1.2 Beginner's Guide

  7. Let's prevent event bubbling from occurring. All we have to do is add this one line of code above the alert() line in step 4.
    alert('You clicked on #' + this.get('id'));
  8. Refresh your HTML document. Click on the child element. You should only see one alert dialog box this time. In effect, we've prevented event bubbling, which is helpful when you only want to run the event's function once, not multiple times.

What just happened?

You've just learned the concept of Event bubbling, which is a useful thing to know because event bubbling can yield unexpected results if you don't keep it in mind. Sometimes you want to run a function only once, so you have to prevent the propagation of the event listener to the parent elements.

We did this by using the stopPropagation MooTools Event method.

Stopping default behavior and event propagation

If you want to stop the default behavior of an element (preventDefault) as well as prevent event propagation(stopPropagation), you should use the stop Event method. This is a combination of both methods and it s a great way to save lines of code if you want to perform both operations.

If you had a link inside a <p> element like so:

<p><a href="http://digg.com">link</a></p>

By default, clicking on this link will take you to the Digg.com website as well as trigger the click event on the <a> element and the <p> element. To prevent this from happening - which in essence means limiting the operation performed only to triggering the click event on the a element and nothing else - you can do the following:


$$('a').addEvent('click', function(e){
e.stop();
});

Using Event Properties

MooTools Event objects also contain a variety of properties. With these properties, you can find out many things about an event. We've already used several of these properties in this article, such as the shift, control, and key properties.

Here are all the properties of event objects. You can find a similar summary in the MooTools official documentation In the Event section: http://mootools.net/docs/core/Native/Event#Event:constructor.

Event Property

Data type

What it does

code

Number

This property returns the key code that was pressed.

You can see a list of JavaScript Key Codes for standard keyboard keys in Mozilla Developer Center, under KeyEvent: https://developer.mozilla.org/en/DOM/Event/UIEvent/KeyEvent

For example, if the user presses the Enter key, a the key code number is 14, and thus event.code will return a number value of 14.

key

String

Returns the lowercase value of the key pressed. For example, it will return q if the Q key is pressed, and enter when the Enter key is pressed.

Possible values of the key property are:

  • letters a - z
  • numbers 0 - 9
  • 'enter', 'up', 'down', 'left', 'right', 'space', 'backspace', 'delete', and 'esc'.

shift

Boolean

This property will return true if the Shift key was pressed.

control

Boolean

This property will return true if the Ctrl key was pressed.

alt

Boolean

This property will return true if the Alt key was pressed.

meta

Boolean

This property will return true if the Meta key was pressed.

wheel

Number

How many times the scoller button on a mouse was used.

page.x

Number

Returns the x coordinate position of the mouse relative to the entire browser window.

page.y

Number

Returns they coordinate position of the mouse relative to the entire browser window.

client.x

Number

Returns the x coordinate position of the mouse relative to the browser's viewport.

client.y

Number

Returns the y coordinate position of the mouse relative to the browser's viewport.

target

Element

Returns the element or elements that are targeted by the event.

relatedTarget

Element

Returns the related element or elements that are targeted by the event (useful for seeing what elements can be affected by event bubbling).

Summary

We learned a lot in this article. We learned about web browser events and how they can help us watch for, and react to, user actions. We saw events in action in web forms and in a mythical web application that allows users to toggle a help tip box with a shortcut key.

Specifically, we covered:

  • Adding event listeners to elements: We learned how to add a single event listener, as well as multiple event listeners, using the addEvent and addEvents methods. You'll find a lot of use for these as you get into the more advanced facets of MooTools.
  • Removing, cloning, and firing off events: We saw how to remove events from elements using the removeEvent and removeEvents methods, cloning events with the clone method, and systematically firing off events, even when they are not triggered by users, using the fireEvent method.
  • Creating custom events: We found out how to create custom events to extend MooTools' event object.
  • Event properties and methods: We saw the available methods and properties that will help us work with events.
[ 1 | 2 ]

If you have read this article you may be interested to view :

MooTools 1.2 Beginner's Guide Learn how to create dynamic, interactive, and responsive cross-browser web applications using this popular JavaScript framework
Published: December 2009
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Jacob Gube

Jacob Gube is a massive MooTools developer. He is the Founder and Chief Editor of Six Revisions, a website dedicated to web developers and web designers. He's also written for other popular web publications such as Read Write Web and Smashing Magazine discussing web technologies and development. A web professional for 8 years, Jacob is an in-house web developer specializing in distance-learning education and web accessibility, using PHP, MooTools, and jQuery to get the job done.

Books From Packt

ADempiere 3.4 ERP Solutions
ADempiere 3.4 ERP Solutions

Beginning OpenVPN 2.0.9
Beginning OpenVPN 2.0.9

Funambol Mobile Open Source
Funambol Mobile Open Source

Apache Roller 4.0 – Beginner's Guide
Apache Roller 4.0 – Beginner's Guide

Tomcat 6 Developer's Guide
Tomcat 6 Developer's Guide

GlassFish Administration
GlassFish Administration

jBPM Developer Guide
jBPM Developer Guide

Apache CXF Web Service Development
Apache CXF Web Service Development

No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
h
j
G
6
z
3
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software