30 Days of Mootools 1.2 Tutorials - Day 5 - Event Handling

- Troy

Event Handling in Mootools 1.2

If you haven’t already, be sure and check out the rest of the Mootools 1.2 tutorials in our 30 days series.

Welcome to Day 5 of 30 Days of Mootools. In the last tutorial we looked at different ways to create and use functions within Mootools 1.2. The next step is to get a grasp on events. Like selectors, events are an essential part of creating an interactive UI. Once you get a hold of an element, you need to then decide what action will cause what effect. Leaving the effects for a later tutorial, lets take a look at that middle step and explore some common events.

Single Left Click

The single left click is the most common event in web development. Hyperlinks recognize the click event and take you to another URL. Mootools can recognize the click event on other DOM elements, giving you tremendous flexibility in design and functionality. The first step is to add the click event to an element:

//$('id_name') defines the element
//.addEvent adds the event
//('click') defines the type of event
$('id_name').addEvent('click', function(){
    //put whatever you want to happen on click in here
    alert('this element now recognizes the click event');
});

You can accomplish the same thing by separating out the function from .addEvent();.

var clickFunction = function(){
    //put whatever you want to happen in here
    alert('this element now recognizes the click event');
}
 
window.addEvent('domready', function() {
    $('id_name').addEvent('click', clickFunction);
});
<body>
    <div id="id_name"> <! -- this element now recognizes the click event -->
    </div>
</body>

Note: Just like the click event recognized by hyperlinks, Mootools’ click event actually recognizes “mouse up,” meaning when you let go of the mouse button, not when you push it down. This is to give users a chance to change their mind by dragging the mouse cursor off of the clicked element before letting the mouse button up.

Mouse Enter & Mouse Leave

Hyperlinks also recognize “hover” events, where the cursor is over the anchor element. With Mootools, you can add a hover event to other DOM elements. By splitting it up into mouseenter and mouseleave, you get greater control over manipulating the DOM upon users’ actions.

Just like before, the first thing we have to do is attach an event to an element

var mouseEnterFunction = function(){
    //put whatever you want to happen in here
    alert('this element now recognizes the mouse enter event');
}
 
window.addEvent('domready', function() {
    $('id_name').addEvent('mouseenter', mouseEnterFunction);
});

Mouseleave works the same way. This event fires when the cursor leaves an element.

var mouseLeaveFunction = function(){
    //put whatever you want to happen in here
    alert('this element now recognizes the mouse leave event');
}
 
window.addEvent('domready', function() {
   $('id_name').addEvent('mouseleave', mouseLeaveFunction);
});

Remove an Event

There are times when you will need to remove an event from an element once it is no longer needed. Removing an event is just as easy as adding one, and even follows a similar structure.

//works just like the previous examples, only replace .addEvent with .removeEvent
$('id_name').removeEvent('mouseleave', mouseLeaveFunction);

Keystrokes in Textarea or Input

Mootools also lets you recognize keystrokes in textareas and inputs. The syntax for this is just like what we saw above:

var keydownEventFunction = function () {
    alert('This textarea can now recognize keystroke events');
};
 
window.addEvent('domready', function() {
    $('myTextarea').addEvent('keydown', keydownEventFunction);
});

The above code will recognize any keystroke. To target a particular keystroke, we need to add a parameter and use an if statement:

//notice the paramater "event" within the function parenthesis
var keyStrokeEvent = function(event){
    // this says, "if the event key that was pressed is equal to "k," do the following."
    if (event.key == "k") {  
	    alert("This tutorial has been brought you by the letter k.") 
    };
}
 
window.addEvent('domready', function() {
    $('myTextarea').addEvent('keydown', keyStrokeEvent);
});

For other controls, such as “shift” and “control,” the syntax is slightly different:

var keyStrokeEvent = function(event){
    // this says, "if the event key that was pressed is "shift," do the following."
    if (event.shift) { 
	    alert("You pressed shift.") 
    };
}
 
window.addEvent('domready', function() {
    $('myTextarea').addEvent('keydown', keyStrokeEvent);
});
<div id="body_wrap">
    <textarea id="myInput"></textarea>
</div>

Example

Here are some working examples of the code we went over above:

Note: try clicking on the single click example, but instead of letting the left click button up, move your cursor off of the block with the button still held down. Notice how it does NOT fire the click event.

var keyStrokeEvent = function(event){
    // this says, "if the event key that was pressed is "k," do the following."
    if (event.key == 'k') { 
	    alert("This Mootorial was brought to you by the letter 'k.'")  
    };
}
 
var mouseLeaveFunction = function(){
    //put whatever you want to happen in here
    alert('this element now recognizes the mouse leave event');
}
 
var mouseEnterFunction = function(){
    //put whatever you want to happen in here
    alert('this element now recognizes the mouse enter event');
}
 
var clickFunction = function(){
    //put whatever you want to happen in here
    alert('this element now recognizes the click event');
}
 
window.addEvent('domready', function() {
    $('click').addEvent('click', clickFunction);
    $('enter').addEvent('mouseenter', mouseEnterFunction);
    $('leave').addEvent('mouseleave', mouseLeaveFunction);
    $('keyevent').addEvent('keydown', keyStrokeEvent);
});
<div id="click" class="block">Single Left Click</div><br />
<div id="enter" class="block">Mouse Enter</div><br />
<div id="leave" class="block">Mouse Leave</div><br />
<textarea id="keyevent">Type the letter 'k'</textarea>
Single Left Click

Mouse Enter

Mouse Leave

To Learn More…

Download a zip with everything you need to get started

Including the Mootools 1.2 core, an external javascript file, a simple html page and a css file.

More about Events

Mootools gives you a lot more control over events than we have covered here. To learn more, check out some of the following links:

Tomorrow’s Tutorial - HTML

Day 6 - Manipulating HTML Elements

Tutorial Request or Questions

The next few tutorials are going to wrap up our basics overview. We are going to start getting into more complex examples and we are interested to hear what kinds of things you want to learn about most. Feel free to drop a note with any suggestions, comments or questions. Thanks and I hope you find this useful.

Bookmark and Share

Comments (11)
  1. Ryan


    In event handling, I think event.stop() could be useful to know about.
  2. Brian


    Good stuff!!! Could you give a "real-world" example of when you would need to use remove an event from an element??
  3. Samay


    Great tutorials, just would like to learn how to AJAX features with php in the later tutorials.
  4. Kent Pilkington


    Here's a related issue that I'm trying to figure out:

    Let's say you set a domready event event function that initializes a drop-down menu. It looks for a certain link, and attaches a mouseenter and mouseleave event to the link that shows or hides another element containing your menu contents.

    When the page initially loads and the domready event is run, the mouse is *somewhere* on the page, possibly even over the element to which you are attaching the events. What I don't yet know is how to detect that this is the case, at which point I could just tell the event to go ahead and fire.

    So, perhaps not an event question strictly speaking, but certainly relevant.
  5. Troy


    @1, you are right Ryan - we will be sure to review that more in depth later in the tutorials. Basically, .stop will let you stop an event from occurring, for example you could add a .click event to a form submission button, then stop that event, and it would stop the form from posting.

    In the meantime, here is a link to the event.stop docs: http://docs.mootools.net/Native/Event#Event:stop

    @2 - the simplest example I can think of is when you want to disable a click. For example, if you have something like a thumbs up button and you want to disable it after a person votes, you can remove the event from the element.

    @3 - Thanks Sammy :) We have an ajax tutorial planned for a bit later in the series (we want to cover a few more subjects before that one, dealing with form elements and form input to name a couple). On the subject, we intend to include some info about the php side of the process.
  6. Troy


    @4 I see what you are talking about Kent, can't say right off, but maybe you could detect the cursor position, then cross reference with the element positions. Could probably get that pretty tight with the Moo, but still doesn't feel like the most elegant solution. Maybe this is an opportunity for a custom event listener or an extension of the mouseover/enter events. Let us play with this one a bit and we will post when we find something.

    Anyone else have any thoughts on this one? Or has anyone found a way to deal with this?
  7. andreas


    @4 This seems to be a very academic question cause domReady is fired very shortly after enter the page. At domready the most images aren't loaded and the user has to oriented on the page. Also it's uncommon that something happens without user interaction. After all no event is fired if the mouse isn't move but inside an element, so if you really want to check this you have to get the position and the dimension of the element and check whether the mouse is inside. Note that dimension and position checking isn't a very fast procedure.
  8. Louis


    @4: Wouldn't a classic mouseover event works where the mouseenter event finds its limits?

    It's an interesting question by the way!
  9. Kent Pilkington


    @7 You are correct that the domready event fires very quickly and the user most likely has not consciously oriented themselves on the page at that time. However, unless they move their mouse off of the browser window between each page load, their mouse is likely to be somewhere on the page when it loads, and thus when the domready event fires. If it is over something is has a mouseenter event, that event doesn't fire until you move off and back on again. (I'm actually dealing with this situation right now on a site that is soon to go into production.)

    @8 I'll have to try that. I could even set it initially to both and use a boolean flag and a couple of if()'s to let mouseover fire once, after which only mouseenter would respond.

    My thanks to both of you.
  10. Tim B


    I'm only on day 5, but this was probably your clearest and most concise tutorial up to this point. Not only is it a great tutorial, but it is a handy reference, too.
  11. Terry


    While experimenting with click detection, I found that only some DOM nodes can have the event associated with them, and it seems to be different for different browsers. Divs and text areas, for instance, typically will throw the click events, but not imgs. I mention this to (hopefully) prevent others from banging their heads against this as I did.


Leave a Reply