Event attributes
In this chapter you will learn:
Event attributes
A jQuery event handler standardizes certain attributes:
.target
represents the DOM element that initiated the event..relatedTarget
represents the other DOM element involved in the event, if any. For mouseout, it indicates the element being entered, and for mousein, it indicates the element being exited..which
indicates the specific key or button that was pressed..pageX
the x coordinate of the mouse cursor relative to the left edge of the page..pageY
the y coordinate of the mouse cursor relative to the top edge of the page..result
the last value returned by an event handler that was triggered by this event, unless the value was undefined..timeStamp
returns the number of milliseconds since January 1, 1970 when the event is triggered..preventDefault()
If this method is called, the default action of the event will not be triggered..stopPropagation()
This method prevents the event from bubbling up the DOM tree looking for more event handlers to trigger.
Returning false from a handler is equivalent to calling both
.preventDefault()
and .stopPropagation()
on the event object.
Using the event object in a handler looks like this:
$(document).ready(function() {
$('#foo').bind('click', function(event) {
alert('The mouse cursor is at ('+ event.pageX + ', ' + event.pageY + ')');
});
});
Passing event data
The optional eventData parameter allows us to pass additional information to the handler.
var message = 'hi!';//from ja v a2 s . c om
$('#foo').bind('click', {msg: message}, function(event) {
alert(event.data.msg);
});
message = 'test!';
$('#bar').bind('click', {msg: message}, function(event) {
alert(event.data.msg);
});
We can also add some extra data before the event handler
function handler(event) {
alert(event.data.foo);
}
$("p").bind("click", {foo: "bar"}, handler)
Next chapter...
What you will learn in the next chapter:
- How to get the keycode from event
- How to listen to the escape key
- How to use event.which to check the key code
- How to convert key code to char