In this tutorial you’ll learn how to use events in jQuery. Events are fundamental to most JavaScript web apps. Using events, your code can respond to things happening in the browser, such as the user clicking a button, entering text into a form field, or submitting a form.
This tutorial isn’t a comprehensive reference, but it includes the stuff that you’ll need when writing the majority of your scripts. Here’s a full list of the jQuery event methods and properties should you need it.
You’ll explore the following topics in this tutorial:
- What is an event?
- Working with events
- A simple event handler example
- Shortcut methods for binding common events
- Accessing the element from within the event handler
- Getting more information about an event
- Stopping default actions and event propagation
- Cancelling event handlers
- Triggering events yourself
What is an event?
Events in JavaScript (and jQuery) occur when something happens to an element in the page. When an event occurs, it is said to have fired. Common events include:
click
- Fired when the user clicks on the element with the mouse
dblclick
- Fired when the user double-clicks on the element with the mouse
mouseover
- Fired when the user moves their mouse pointer over the element
load
- Fired when the element — for example, an image — has fully downloaded
submit
- Fired when a form is submitted (this event only occurs for
form
elements)
Working with events
To work with an event in jQuery, you first create a function called an event handler that will deal with the event when it occurs. Then you call a jQuery method to bind your event handler function to a particular event for a selected element (or elements).
There are many jQuery methods to bind events, as you’ll see in a moment, but the main one is bind()
. This takes an event name and a function name as arguments, and binds the function to that event for the selected element(s):
$(selector).bind( eventName, functionName );
Then, when the event occurs for that element, your event handler function is triggered — that is, called automatically — and the function can process the event as required.
A simple example
The following example shows how to create a simple event handler function and bind it to the click
event of a form button:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$( init );
function init() {
$('#myButton').bind( 'click', sayHello );
}
function sayHello() {
alert( "Hello there!" );
}
</script>
</head>
<body>
<div>
<input type="button" id="myButton" value="Click Me" />
</div>
</body>
</html>
When you click the button in the page, an alert box pops up with the message “Hello there!”.
Shortcut methods for binding common events
To make life easy, jQuery provides many shortcut methods for binding commonly-used events to event handlers. Here are a few:
click( functionName )
- Equivalent to
bind( 'click', functionName )
dblclick( functionName )
- Equivalent to
bind( 'dblclick', functionName )
load( functionName )
- Equivalent to
bind( 'load', functionName )
For example, you could rewrite the call to bind()
in the example above as follows:
$('#myButton').click( sayHello );
You can find a full list of shortcut methods in the jQuery documentation for bind()
.
Accessing the element from within the event handler
When an element’s event triggers your event handler function, you can retrieve the element as a DOM element object from within the handler by using the keyword this
. This means you can find out more about the element whose event was fired, manipulate the element, and so on.
The following example makes a button pulsate (fade out then fade back in) when clicked. To do this, the event handler accesses the clicked button object via this
, wraps it in a jQuery object, then calls the jQuery fadeOut()
and fadeIn()
methods on the object to fade it out and back in:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$( init );
function init() {
$('#myButton').bind( 'click', pulsate );
}
function pulsate() {
$(this).fadeOut();
$(this).fadeIn();
}
</script>
</head>
<body>
<div>
<input type="button" id="myButton" value="Click Me" />
</div>
</body>
</html>
Getting more information about an event
Often your event handler doesn’t need to know much about the event that triggered it in order to do its job. If it needs more details of the element that fired the event, it can use the this
keyword as described above. However, jQuery can give you a lot more information about an event if you need it.
To get all the details of an event, your event handler function should accept a jQuery event
object as an argument. The event handler can then access the event information by using various properties and methods of this object.
The following example not only pops up an alert box when the button is clicked, but also displays the exact date and time when the click occurred, as well as the X and Y coordinates of the mouse pointer at the time:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$( init );
function init() {
$('#myButton').bind( 'click', displayInfo );
}
function displayInfo( clickEvent ) {
var clickTime = new Date( clickEvent.timeStamp );
var clickTimeString = clickTime.toDateString() + " at " + clickTime.toTimeString();
var mouseCoords = "(" + clickEvent.pageX + "," + clickEvent.pageY + ")";
alert( "Hi there! You clicked the button on " + clickTimeString +
".nnYour mouse coordinates were " + mouseCoords + "." );
}
</script>
</head>
<body>
<div>
<input type="button" id="myButton" value="Click Me" />
</div>
</body>
</html>
The above script uses 3 properties of the event
object:
timeStamp
- The timestamp when the event occurred
pageX
- The X coordinate of the mouse pointer at the time of the click, relative to the top left hand corner of the document
pageY
- The Y coordinate of the mouse pointer at the time of the click, relative to the top left hand corner of the document
Find out more about the event
object, including all its properties and methods, in the jQuery documentation.
Stopping default actions and event propagation
Events in JavaScript have a couple of notable features:
- Default actions. Many events have a default action. For example, if a user clicks a link, the default action for the link’s
click
event is to open the link. - Event propagation. Also known as event bubbling, this occurs when you bind event handlers for the same event to both an element and its parent. For example, you might bind an event handler to a link’s
click
event, and bind another handler to theclick
event of the paragraph containing the link. When the user clicks the link, the link’sclick
event handler is triggered first, then the event “bubbles up” to the parent paragraph, triggering the paragraph’sclick
event handler.
There’s an alternative to event bubbling, known as event capturing. Here’s a great discussion on the two approaches. jQuery uses the event bubbling approach.
Often it’s useful to prevent default actions and/or event propagation from occurring. For example, if you’ve set up a click
handler on a link that needs to check that a form has been completed before leaving the page, you want to stop the browser from following that link by default.
Similarly, if you’ve set up click
handlers on a parent element as well as each of its children, you may not want both parent and child handlers to be triggered at the same time.
jQuery’s event
object gives you a couple of methods you can use to stop these things happening:
preventDefault()
- Stops the event’s default action from occurring
stopPropagation()
- Stops the event from bubbling up to the element’s parent
The following example opens a link in a new window when clicked, and uses preventDefault()
to stop the link also being opened in the current window:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$( init );
function init() {
$('#myLink').bind( 'click', openInWindow );
}
function openInWindow( clickEvent ) {
window.open( this.href, '', 'width=500,height=400' );
clickEvent.preventDefault();
}
</script>
</head>
<body>
<div>
<a id="myLink" href="http://www.example.com/">Click me</a>
</div>
</body>
</html>
You can also stop both the default action and event propagation from occurring simply by returning false
from your event handler function.
Cancelling event handlers
If you want to remove event handlers from an element, call unbind()
. To remove all event handlers, write:
$(selector).unbind();
To remove the handler for a specific event, write:
$(selector).unbind( eventName );
Triggering events yourself
Occasionally it’s useful to be able to trigger an element’s event explicitly from your code. For example, you might want to submit a form automatically when the user clicks a link.
jQuery’s trigger()
method triggers a particular event for the selected element(s). You pass the event name to trigger as an argument.
Here’s an example that submits a form when the user clicks a link in the page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$( init );
function init() {
$('#myLink').bind( 'click', sendForm );
}
function sendForm() {
$('#myForm').trigger('submit');
return false;
}
</script>
</head>
<body>
<form id="myForm" method="post" action="handler.php">
<div>
<label for="email">Email address:</label>
<input type="text" name="email" />
<a id="myLink" href="#">Send</a>
</div>
</form>
</body>
</html>
You can also trigger events using the same shortcut methods you use for binding common events (as described earlier in the article). To do this, simply call the shortcut method without passing any arguments. For example:
$('#myLink').click(); // Trigger #myLink's click event
$('#myForm').submit(); // Trigger #myForm's submit event
Summary
In this tutorial you’ve learned how to work with events in jQuery. You’ve looked at:
- The concept of events and event handlers
- How to bind an event handler to an event for a particular element
- Accessing an event’s element from inside the event handler
- Accessing event information such as timestamps and mouse position
- Default actions and event propagation, and how to stop them
- How to remove an event handler, and
- How to trigger events within your code.
Events are very powerful and useful, and jQuery does a great job at making events easy to work with. Now you’ve read this tutorial, you’re well on your way to creating rich, interactive web applications using jQuery.
Happy coding!
Leave a Reply