An Introduction to Event Handling in jQuery [con't]
Triggering Events in jQuery Programmatically
You can also trigger events programmatically. The following code snippet illustrates how you can trigger the click event on a button control programmatically:
However, in this case, after the event has been executed, the default browser action would also execute. The triggerHandler
method shown next would execute the event attached to the DOM element but would not execute any default browser action.
Assigning code to an event is also simple. Here's an example:
event.preventDefault()
,event.isDefaultPrevented()
,event.stopPropagation()
,event.isPropagationStopped()
,event.stopImmediatePropagation()
, and event.isImmediatePropagationStopped()
.
The following code snippet shows how you can work with the properties of the event object in jQuery:
Note that the event object in jQuery has a target property that corresponds to the DOM element that has been clicked. The following code snippet shows how you can use this property to retrieve the event target:
You can also create a new event object that is W3C DOM compliant. Here is how you can do that:
These are the most important and commonly used members of the jQuery Event Object and their purposes:
type
: This is used to retrieve the event name.target
: This is used to retrieve a reference to the DOM element on which the event occurred.pageX
: This is used to retrieve the X mouse coordinate relative to the document.pageY
: This is used to retrieve the Y mouse coordinate relative to the document.preventDefault
: This is used to cancel the default browser action after an event is triggered.stopPropagation
: This is used to stop event bubbling but doesn't stop the default browser action from executing.
Commonly Used Event Methods in jQuery
These are the most commonly used event methods in jQuery and their purposes:
bind
: This method is used to bind a function to one or more events for each element contained in the wrapped set.live
: This method is used to bind a particular event handler to all current and future elements of the wrapped set.one
: This method is similar to bind except that any event handler is automatically removed after it has been executed once.trigger
: This method is used to execute a particular event for each element in the wrapped set.triggerHandler
: This method is used to execute a particular event on one element in the wrapped set.unbind
: This method is used to remove previously bound events from each element in the wrapped set.
Suggested Readings
Summary
This article was just an introduction to working with events in jQuery. I will explore more on the Event Handling API in future articles. Happy coding!
Original: December 2, 2010