Working with Events in MooTools: Part 2

0
83
9 min read

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.

LEAVE A REPLY

Please enter your comment!
Please enter your name here