public this Crafty.addEvent(Object ctx, HTMLElement obj, String event, Function callback)

Context of the callback or the value of this


Element to add the DOM event to


Event name to bind to


Method to execute when triggered

Adds DOM level 3 events to elements. The arguments it accepts are the call context (the value of this), the DOM element to attach the event to, the event name (without on (click rather than onclick)) and finally the callback method.

If no element is passed, the default element will be window.document.

Callbacks are passed with event data.

Note: This is related to DOM events only, not Crafty's own event system. Of course, you can trigger Crafty events in the callback function!


Normally you'd use Crafty's built-in mouse component, but for the sake of an example let's pretend that doesn't exist. The following code will add a stage-wide MouseDown event listener to the player, and log both which button was pressed and the (x,y) coordinates in viewport/world/game space.

var player = Crafty.e("2D");
    player.onMouseDown = function(e) {
        Crafty.log(e.mouseButton, e.realX, e.realY);
Crafty.addEvent(player, Crafty.stage.elem, "mousedown", player.onMouseDown);