Events

The Events class is a collection of functions for handling events across browsers. Here is the documentation for Event.js.

Whenever you add an event to a DOM element (not to be confused with the //Events// class in Class.Extras) the argument passed to that function will be the event native. This has been extended like other natives to have additional properties by MooTools.

Properties

shift
true if the user pressed the shift
control
true if the user pressed the control
alt
true if the user pressed the alt
meta
true if the user pressed the meta key
code
the keycode of the key pressed
page.x
the x position of the mouse, relative to the full window
page.y
the y position of the mouse, relative to the full window
client.x
the x position of the mouse, relative to the viewport
client.y
the y position of the mouse, relative to the viewport
key
the key pressed as a lowercase string. key also returns 'enter', 'up', 'down', 'left', 'right', 'space', 'backspace', 'delete', 'esc'. Handy for these special keys.
target
the event target
relatedTarget
the event related target

$('eventExample').addEvent('keydown', function(event){
    console.log(event.key); /*returns the lowercase letter pressed*/
    console.log(event.shift); /*returns true if the key pressed is shift*/
    if (event.key == 's' && event.control) console.log('document saved');
});
execute this code

Event.stop, .preventDefault & .stopPropagation

Event.stop will stop an Event from propigating and will also execute .preventDefault

Event.preventDefault will prevent the default action of the event from completing (for example, clicking a url and executing .preventDefault will still execute the onclick event(s) attached to the link, but will NOT follow the link).

Event.stopPropagation will execute the default behavior and any events (such as onclick) attached to the element but will not allow the event to bubble up through the DOM (so that if there is an event attached to document.body.onclick and the user clicks a link, the link's events will fire, but the event on the document.body will not).

Event.keys

MooTools defines a handful of key codes but you can add more definitions for special uses. This allows you to add event handlers for those keys:

Event.Keys.whatever = 80;
$(myelement).addEvent(keydown, function(event){
    if (event.key == 'whatever') console.log(whatever key clicked).
});

By default, MooTools defines the following keys:

  • enter - 13
  • up - 38
  • down - 40
  • left - 37
  • right - 39
  • esc - 27
  • space - 32
  • backspace - 8
  • tab - 9
  • delete - 46

mootorial/03-native/05-event.txt · Last modified: 2011/01/14 03:53 by ralph