Working with Events in MooTools: Part 1

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

In this two-part article by Jacob Gube, we'll be exploring browser events; we'll see how MooTools can help us watch out for events such as mouse clicks, mouse movements, keyboard presses, and all the events that make our web pages more responsive to user actions.

In this article, we shall:

  • Define what events are in web development terms
  • Learn how to add event listeners to web page elements
  • Find out how to create custom events to extend MooTools' Event object
  • Learn how to remove, clone, and fire off events
  • Investigate MooTools Events methods and properties

We have a lot of things to cover in this article, so hold on to your seats and enjoy the ride!

What are Events, Exactly?

Events are simply things that happen in our web pages. MooTools supports all HTML 4.01 event attributes like onclick and onmouseout, but the framework refers to them without the "on"  prefix (click instead of onclick, mouseout instead of onmouseout).

What's neat about MooTools is that it not only extends HTML 4.01 event attributes with a few of its own, but also ensures that methods and functions that deal with web page events work across all web browsers by providing us with a solid, built-in object called Events. Event is part of the Native component of MooTools, and is also referred to as the Event hash.

You can read the official W3C specifications on events, in the HTML 4.01 Specification, section 18.2.3, under Intrinsic Events:http://www.w3.org/TR/html401/interact/scripts.html#h-18.2.3

We'll go over all of the available event attributes in MooTools so you can learn what stuff we can listen to. There are several events that we can detect or "listen to". We can, for the sake of discussion, divide them into five groups: window events, form events, keyboard events, mouse events, and MooTools custom events.

Window Events

Window events refer to activities that occur in the background. There are only two window events.

HTML Event attribute / MooTools event name

What is it?

onload / load

This event occurs when the window and images on the page has fully loaded and/or when all of the iFrames in the page have loaded. It can be used for monitoring when the web page has fully loaded (such as when you want to know if all images have been downloaded).

onunload / unload

This even happens when a window or an iFrame is removed from the web page. It has limited use.

Form events

There are events that occur within Form elements (such as <input> elements), and we'll refer to these as form events.

For example, the onfocus  event is triggered when the user clicks on an input field (you'll see this in action in this article), effectively focusing on that particular input field. Some of these events apply event to non-form elements.

HTML Event attribute / MooTools event name

What is it?

onblur / blur

This event occurs when an element loses focus, either because the user has clicked out of it, or because the user used the Tab key to move away from it. This is helpful for monitoring the instant the user loses focus on a particular element.

onchange / change

This event happens when the element loses focus or when its original value has changed. This is helpful for knowing when the user starts typing in a input text field or textarea, or when a user selects a different option in a select drop-down element.

onfocus / focus

This event is the opposite, of the blur event: it is triggered when the user focuses on an element. This is useful for watching when the user highlights a form field or when they have navigated to it using the Tab key.

onreset / reset

This event only applies to form elements. This event is triggered when the form has been reset to its default values.

onselect / select

This event happens when the user highlights (selects) text in a text field.

onsubmit / submit

This event is only for form elements. This event occurs when the user submits a web form.

Keyboard events

There are events that happen when a user presses on a keyboard input device; let's call these keyboard events.

For example, the onkeypress event is triggered when you press any key on your keyboard.

HTML Event attribute / MooTools event name

What is it?

onkeydown / keydown

This event occurs when the user holds down a keyboard key.

onkeypress / keypress

This event is triggered whenever the user presses a keyboard key.

onkeyup /keyup

This event happens when the user releases a key.

Mouse events

There are several HTML event properties that allow you to deal with activities related to the mouse. Clicking, moving, double-clicking, and hovering are all mouse events.

HTML Event attribute / MooTools event name

What is it?

onclick / click

This event occurs whenever the user uses the mouse button to click on an element.

ondblclick / dblclick

This even occurs whenever the user double-clicks on an element.

onmousedown / mousedown

This event occurs when the mouse button is held down.

onmouseup / mouseup

This even occurs when the mouse button is released.

onmousemove / mousemove

This event occurs when the mouse is moved.

onmouseout / mouseout

This event occurs when the mouse pointer is removed from the target element.

onmouseover / mouseover

This event occurs when the mouse pointer enters the target element.

MooTools Custom Mouse Events

MooTools supplies us with three custom events that extend the standard mouse events.

MooTools event name

What is it?

mouseenter

This event is triggered when the user's mouse pointer enters an element, but does not fire again when the mouse goes over a children element (unlike mouseover). This is useful for detecting the mouseover event once in nested element structures, such as <li><a>item</a></li>. If we were to use the mouseover event, it would be triggered twice, once for <li> and once again for <a>.

mouseleave

This event works similarly to mouseenter in that it is triggered only once when the mouse pointer exits the target element. Unlike the mouseout event, which will be triggered more than once for nested element structures.

mousewheel

This even is triggered when the scroller on a mouse is used (available in most modern mice input devices, usually situated in between the left and right mouse buttons).

Adding Event Listeners

We can attach event listeners to elements on a web page using the addEvent and addEvents method. 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.

Adding a single event listener

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(){
alert('You clicked on a hyperlink');
});

In a moment, we'll create a simple web form the highlights the input field that the user is focused on.

Time for action – Highlighting focused fields of web forms

  1. Let's start with our web form's HTML. We'll use <input> and <textarea> tags that will hold our user's information as well as provide them a means to submit the web form (input type="button").We use the <label>  tag to indicate to the user what information to put inside each form field.
    <form action="" method="get">
    <p><label for="Name">Name: </label>
    <input name="Name" type="text"></p>
    <p><label for="Email">Email: </label>
    <input name="Email" type="text"></p>
    <p><label for="Comment">Comment: </label>
    <textarea name="Comment" cols="" rows=""></textarea></p>
    <p><input name="Submit" type="button" value="Submit"></p>
    </form>

    With the above markup, this is how our form looks like:

    MooTools 1.2 Beginner's Guide

  2. Our web form is a bit dull, so how about we spruce it up a bit with some CSS? Read the comments to gain insight on some of the more important CSS properties to take a note off.
    /* Center the fields using text-align:center */
    form {
    width:300px;
    border:1px solid #b1b8c2;
    background-color:#e3e9f2;
    text-align:center;
    padding:25px 0;
    }
    label {
    display:block;
    font:12px normal Verdana, Geneva, sans-serif;
    }
    /* Give the input and textarea fields a 1px border */
    input, textarea {
    width:250px;
    border:1px solid #5c616a;
    }
    textarea {
    height:100px;
    }
    p {
    text-align:left;
    display:block;
    width:250px;
    overflow:auto;
    padding:0;
    margin:5px 0;
    }
    /* We will give fields that are currently focused on the .focus
    class which will give them a distinct thicker border and
    background color compared to the other input fields */

    .focused {
    border:3px solid #b1b8c2;
    background-color: #e8e3e3;
    }

  3. With just a few styles, our simple web form has transformed to a more attractive form field.

    MooTools 1.2 Beginner's Guide

  4. Let us move onto the JavaScript. We use the addEvent method to add an event listener for the form event, onfocus. When the user focuses on a particular field, we run a function that adds the .focus CSS class on that field we declared as a style rule in step 2. We'll also remove .focus class on other fields on the web page.

    window.addEvent('domready', function(){
    var els = $$('input, textarea')
    els.addEvent('focus', function(){
    els.removeClass('focused');
    this.addClass('focused');
    })
    });

    Now, when you focus on a form field, it will be highlighted with a thick blue border and with a lighter blue background. Users who use the Tab key to navigate in between form fields will appreciate this feature since they'll clearly see which field is active.

    MooTools 1.2 Beginner's Guide

What just happened?

In the previous example, we created a simple and interactive web form that highlights the current field the user has active. We did this by using the addEvent method, adding an event listener for the focus form event. When the user focuses on a particular input field, we ran a function that adds the .focusCSS class which highlights the focused field <input> or <textarea>with a thick blue border with a light blue background.

By highlighting active fields in a web form, we have just improved our form's usability by providing visual feedback about which field the user is currently on.

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:

Adding multiple event listeners

The addEvents method allows you to add more than one event listener to an element (or set of elements). This is the format for running the addEvents method on an element.


$(yourelement).addEvents({
'event1' : function {},
'event2' : function {}
})

Let's explore the addEvents method using the web form example above.

Time for action – Adding tooltips to the web form

We'll use the same web form as before, but we'll modify it to provide a hover over tooltip to users. This can be used to provide more explanation for a particular field. Although the example we're using is pretty straightforward, there are some web forms that have labels that could use a little tooltip help to clarify to the users what they need to enter.

  1. First, we have to modify our HTML. We'll add a tag with the text (?), which when the user hovers over them, will display a relevant tooltip/information box beside our web form. We give each of these span tags a unique ID so that we can tell MooTools which help text to display. The tooltip/information box is a div, width the ID of feedback.

    <form action="" method="get">
    <p><label for="Name">Name: <span class="help" id="hName">(?)
    </span></label><input name="Name" type="text" /></p>
    <p><label for="Email">Email: <span class="help" id="hEmail">(?)
    </span></label><input name="Email" type="text" /></p>
    <p><label for="Comment">Comment: <span class="help"
    id="hComment">(?)</span></label><textarea name="Comment"
    cols="" rows=""></textarea></p>
    <p><input name="Submit" type="button" value="Submit" /></p>
    </form>
    <!-- holds user feedback -->
    <div id="feedback">&nbsp;</div>
  2. Let's give our new elements some CSS styles.
    #feedback {
    width:200px;
    border:1px solid #f90;
    background-color:#ffc;
    padding:5px;
    font:bold 12px Verdana, Geneva, sans-serif;
    /* Displays the div to the right of our web form */
    position:absolute;
    top:15px;
    left:315px;
    }
    .help {
    color:#009;
    font:bold 12px Arial, Helvetica, sans-serif;
    /* Changes mouse cursor to pointer when mouse hovers on .help */
    cursor:pointer;
    }
  3. It's time for some MooTools code. First, we should hide the #feedback div.
    $('feedback').setStyle('opacity', 0);
  4. Let's create an array object called helptext that will hold our help text that we will display. For their index, we use the ID of the .help span tag for each input field, so that we easily reference the array position later on.

    // Initialize helptext array, will store help text
    var helptext = {};

    // Put help text inside array
    Helptext.hName = 'Enter your first and last name';
    Helptext.hEmail = 'Enter a valid email address';
    Helptext.hComment = 'Leave your feedback';

  5. Next we'll add two event listeners using the .addEvents() method. The first event listener is for mouseover when the user puts their mouse cursor over a .help span element, we show tween the #feedback div in, and give it the associated text.
    'mouseover' : function() {

    // Get the span's ID
    var spanID = $(this).get('id');

    // Set the text inside feedback div, reference
    // array index using spanID
    $('feedback').set('html', helptext[spanID]);

    $('feedback').tween('opacity', 1);

    }
  6. The second event listener that we add to our span elements is mouseout; when the user removes their mouse cursor from a span tag, it will hide the #feedback div.
    'mouseout' : function() {
    $('feedback').tween('opacity', 0);
    }
  7. Our addEvent() code block now looks like this:

    $$('.help').addEvents({
    'mouseover' : function() {
    $('feedback').tween('opacity', 1);
    // Get the span's ID
    spanID = $(this).get('id');
    // Set the text inside feedback div, reference
    // array index using spanID
    $('feedback').set('html', helptext[spanID]);
    },
    'mouseout' : function() {
    $('feedback').tween('opacity', 0);
    }
    });

    Our form should now look like this:

    MooTools 1.2 Beginner's Guide

  8. Here is the entire MooTools script:
    window.addEvent('domready', function(){
    $('feedback').setStyle('opacity', 0);
    $$('input, textarea').addEvent('focus', function(){
    $$('input, textarea').removeClass('focused');
    $(this).addClass('focused');
    });
    // Initialize helptext array, will store help text
    var helptext = [];
    // Put help text inside array
    helptext['hName'] = 'Enter your first and last name';
    helptext['hEmail'] = 'Enter a valid email address';
    helptext['hComment'] = 'Leave your feedback';
    // Add events to span.help
    $$('.help').addEvents({
    'mouseover' : function() {
    $('feedback').tween('opacity', 1);
    // Get the span's ID
    spanID = $(this).get('id');
    // Set the text inside feedback div, reference
    // array index using spanID
    $('feedback').set('html', helptext[spanID]);
    },
    'mouseout' : function() {
    $('feedback').tween('opacity', 0);
    }
    });
    });

  9. When you hover over a (?), you should see something similar to the following image:

    MooTools 1.2 Beginner's Guide

What just happened?

In the previous example, we discovered how to add more than one event listener to an element using the .addEvents() method.

Creating Custom Events

Besides the standard HTML events that you saw earlier in this article, you can also create custom events of your own. For example, you may want to create a custom event for a user pressing the Caps lock key or you can do this by adding (extending) properties to the Element.Events object in MooTools. Here are the format for adding event properties to the Element.Events MooTools object:


Element.Events.eventname = {
'base' : 'click', // A base event such as click, keypress,
keydown, onload, etc.
'condition' : function() {
// conditions that need to be met to trigger event
},
'onAdd' : function() {
// Functions to trigger when you bind/add the event to elements
},
'onRemove' : function() {
// Functions to execute when you unbind/remove elements
}
};

There are five things to take a note off in the above code sample.

  • eventname: this is the name of the your custom event.
  • base: this is an optional string value which gives our custom event a standard event to listen to. If you have condition set, which is also an optional property, then you must also have base set.
  • condition: this is a function that must be met to trigger the event; in other words, the function must return a boolean value of 'true' in order for the event to fire. This is an optional property to set, but if you have condition set, you must also have base set.
  • onAdd is an optional function property; it fires of the function that you assign to it whenever the custom event is added or binded to elements.
  • onRemove is an optional function property; it does the opposite of onAdd, if the custom event is removed or unbinded from elements, then it will trigger the function.

There's really no better way to learn about creating custom events than by creating one. That's what we'll do next!

Time for action – Creating a custom event for showing help tips

Imagine that you created a web application that supports keyboard shortcuts. Keyboard shortcuts allow users to use web applications more efficiently. For this example, let us say that one of your keyboard shortcuts is Shift + H, which displays a box with help tips in it.

  1. First step, let's set up the HTML for our help tip box. Our help tip box will be a
    with an ID of help.
    <body>
    <h1>myWebApp</h1>
    <p>Use <strong>Shift + H</strong> to view Help tips on how to
    use this web application.</p>
    <div id="help">
    <h1>Help Tips</h1>
    <p>This is the help tip box. It will display helpful tips on
    how to use this web application.</p>
    <p>Press <strong>Shift + H</strong> on the keyboard to
    toggle this box.</p>
    </div>
    </body>
  2. Let's give the help tip box some styles, as well as change the default font style of the HTML web page with some CSS. Let us give the help tip box a gray background with a dotted border to make it easy to distinguish. This step is optional.
    body {
    font:12px solid Verdana, Geneva, sans-serif;
    }
    #help {
    width:200px;
    background:#ccc;
    padding:5px;
    border: 1px dotted #00f;
    }
  3. It's time for MooTools to step in. The first thing we'll do is hide the help tip box. We'll do this using the .setStyle() MooTools method, setting the opacity property to 0.
    $('help').setStyle('opacity', 0);
  4. Next, we'll create our custom event. This custom event will be called shiftH. We'll use the base event keypress so that whenever you press something on the keyboard, the event will check to see if the appropriate keys are pressed (Shift and H keys at the same time).

    // Add custom event to MooTools Events object
    Element.Events.shiftH = {
    // Set our base event to 'keypress'
    base: 'keypress'
    };
  5. We should set the condition for this custom event. We want to event to be triggered whenever you have pressed Shift and H at the same time. We can use the MooTools Event property called .shift which returns a Boolean value of true if the Shift key is pressed.

    We will also use the .keyEvent property that returns a string that has the value of the key that was pressed in lowercase. In our instance, if the .key property should be equal to 'h'.

    Both Shift and H must be pressed at the same time. In other words, our custom event (shiftH) will not be triggered when you press H without also pressing Shift(and vice versa). Therefore, the condition will return the true value only when customEvent.shift is true and customEvent.key=='h' is true.


    // Add custom event to MooTools Events object
    Element.Events.shiftH = {
    // Set our base event to 'keypress'
    base: 'keypress',
    // Condition that must be met
    condition: function(customEvent){
    if(customEvent.shift && customEvent.key=='h'){
    return true;
    else{
    return false;
    }
    }
    };
  6. The only thing that is left is adding an event listener for shiftH. We'll use the addEvent method, that will run a function that toggles the #help div.

    // Add custom event on document object
    window.addEvent('shiftH', function(){
    // execute the stuff in here
    });
  7. The code we want to execute when the shiftH event is triggered is showing the #help div when it's hidden, and vice versa; in other words, we want to toggle the opacity of #help div. We'll transition the opacity using the .tween() method.

    We'll create a variable for the opacity value we want to assign to the #help div; opacityValue. If the current opacity is 0, then opacityValue will be 1. If the current opacity is 1, then opacityValue will be 0. Then we tween the #help div opacity property to opacityValue.

    // If opacity is 0 then we tween to 1, and vice versa
    var opacityValue = ($('help').get('opacity')) == 0 ? 1 : 0;
    $('help').tween('opacity', opacityValue);

  8. All together, our MooTools script looks is:
    window.addEvent('domready', function(){
    $('help').setStyle('opacity', 0);
    // Add custom event to MooTools Events object
    Element.Events.shiftH = {
    // Set our base event to 'keypress'
    base: 'keypress',
    // Event condition
    condition: function(customEvent){
    if(customEvent.shift && customEvent.key=='h') return true;
    }
    };
    // Add custom event on document object
    window.addEvent('shiftH', function(e){
    // If opacity is 0 then we tween to 1, and vice versa
    var opacityValue = ($('help').get('opacity')) == 0 ? 1 : 0;
    $('help').tween('opacity', opacityValue);
    });
    });
  9. Test your web page in your favorite web browser. Then toggle the help tip box by pressing Ctrl + H.

    MooTools 1.2 Beginner's Guide

What just happened?

You've just discovered how to create a custom event by extending the MooTools Event object. We created a custom event called shiftH which had a base event of keypress. The condition that must be met for shiftH to be triggered is that both the Shift key and the H key is pressed at the same time.

Additionally, we were able to explore two MooTools Events method included inside Events: .shift which returns true if the Shift key was pressed, and .key which returns a lowercase string value of the key that is pressed.

Have a go hero – create your own custom event

Why don't you try to create your own custom event? How about modifying shiftH to ctrlH and so that #help` div is toggled when your users press ctrl + H.

You can see what other Event methods are available to you in the official MooTools documentation of Event: http://mootools.net/docs/core/Native/Event#EventIn this instance you'll have to replace the .shift Event method to .control Event method.

>> Continue Reading Working with Events in MooTools: Part 2

 

[ 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.
3
v
B
E
6
7
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