The object Eventis passed to the event handler with a number of parameters related to the event. Then, in the handler, we can extract the values of these parameters and somehow apply them during processing.
Some common properties of the Event object:
- currentTarget: the current element on which the event is handled
- data: represents an object to which additional data associated with the event is passed, for example, in the bind method
- target: the element that fired the event
- timestamp: event time
- pageX: coordinates of the mouse pointer relative to the left border of the document
- pageY: coordinates of the mouse pointer relative to the top border of the document
- which: in keyboard or mouse event handlers, an object containing data about the pressed key or button
For example, let’s process pressing the pages of keyboard keys and get the pressed key:
$(function(){ $(document).bind('keydown', function(e){ console.log(e.which); }); });
Here we register a keyboard handler for the whole document and in case of pressing the console, a numeric key code will be displayed. Having received this numerical code, we can perform some actions.
Passing data to the handler
Using the bind method, we can pass data to the event’s data parameter as an optional second parameter:
var mes = 'Hello world!'; $('button').bind('click', mes, function(e){ alert(e.data); });
In this case, the mes variable will be passed to the e.data property, from which we can then get its value.
The Event object also provides a number of methods:
- preventDefault(): Cancels all actions that this event does by default. For example, when clicking on a link, we can use this method to disable the transition to this link.
- isDefaultPrevented(): returns true if the preventDefault method has already been called for this event
- stopPropagation(): prevent the event from bubbling up the DOM hierarchy and processing it further.
- isPropagationStopped(): returns true if the stopPropagation method has already been called before