Event object
The event object
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!';
$('#foo').bind('click', {msg: message}, function(event) {
alert(event.data.msg);
});
message = 'test!';
$('#bar').bind('click', {msg: message}, function(event) {
alert(event.data.msg);
});
add some extra data before the event handler
function handler(event) {
alert(event.data.foo);
}
$("p").bind("click", {foo: "bar"}, handler)
Home
JavaScript Book
jQuery
JavaScript Book
jQuery
Event:
- jQuery Event
- jQuery's methods for event
- Event object
- event.keycode
- event.clientX/clientY
- event.pageX/pageY: click event coordinates
- event.preventDefault()
- event.stopPropagation(): Stop only an event from bubbling by using the stopPropagation method.
- event.target.tagName
- event.which:check key code
- return false to Cancel a default action and prevent it from bubbling up
- bind
- .blur()
- .change()
- .click()
- .error()
- .dblclick()
- .delegate()
- die:Removes a bound live event
- .focus()
- .hover()
- keydown() event
- .keypress()
- keyup event and check the key code
- .live()
- .load()
- mousedown() event
- mouseenter() event
- mouseleave
- mousemove()
- mouseover() event
- mouseout
- mouseup() event
- .off() removes events
- .on() replaces the functionality of all the event methods.
- .one() method executes handler only once.
- .ready()
- .resize()
- .scroll()
- .select()
- .submit()
- .toggle()
- .trigger()
- .triggerHandler()
- .unbind() accepts a string describing the event type to unbind.
- .undelegate() removes the binding
- .unload()
- use bind/trigger to create custom event