Skip to content

Commit 2a8734d

Browse files
committed
Rewrote the page on Handling Events
Replaced all references to .bind() with .on() Removed less desirable event helpers. Documented all of .on()'s capabilities. Linked to most other pages in the event section for more details
1 parent 9236ea3 commit 2a8734d

File tree

1 file changed

+107
-62
lines changed

1 file changed

+107
-62
lines changed

page/events/events-to-elements.md

Lines changed: 107 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,108 +1,153 @@
11
---
2-
title : Connecting Events to Elements
2+
title : Handling Events
33
attribution: jQuery Fundamentals
44
---
5-
jQuery offers convenience methods for most common events, and these are the
6-
methods you will see used most often. These methods — including `$.fn.click`,
7-
`$.fn.focus`, `$.fn.blur`, `$.fn.change`, etc. — are shorthand for jQuery's
8-
`$.fn.bind` method. The bind method is useful for binding the same handler
9-
function to multiple events, when you want to provide data to the event hander,
10-
when you are working with custom events, or when you want to pass an object of
11-
multiple events and handlers.
12-
13-
```
14-
// Event binding using a convenience method
15-
$('p').click(function() {
16-
console.log('click');
5+
jQuery provides a method `.on()` to
6+
respond to any event on the selected elements. This is called an _event binding_.
7+
Although `.on()` isn't the only method provided for event binding, it is a best
8+
practice to use this for jQuery 1.7+. See history of event binding for more info.
9+
<!-- TODO: link to history page -->
10+
11+
The on method provides several useful features:
12+
<ul>
13+
<li><a href="#simple-event-binding">Bind any event triggered on the selected elements to an event handler</a></li>
14+
<li><a href="#multiple-events-one-handler">Bind multiple events to one event handler</a></li>
15+
<li><a href="#multiple-events-multiple-handlers">Bind multiple events and multiple handlers to the selected elements</a></li>
16+
<li><a href="#event-object">Use details about the event in the event handler</a></li>
17+
<li><a href="#passing-data">Pass data to the event handler for custom events</a></li>
18+
<li><a href="#event-delegation">Bind events to elements that will be rendered in the future</a></li>
19+
</ul>
20+
### Examples
21+
22+
#### <a name="simple-event-binding">Simple event binding</a>
23+
```
24+
// When any <p> tag is clicked, we expect to see '<p> was clicked' in the console.
25+
$('p').on('click', function() {
26+
console.log('<p> was clicked');
1727
});
1828
```
1929

30+
#### <a name="multiple-events-one-handler">Many events, but only one event handler</a>
31+
32+
Suppose you want to trigger the same event whenever the mouse hovers over or leaves
33+
the selected elements. The best practice for this is to use "mouseenter mouseleave".
34+
Note the difference between this and the next example.
35+
36+
```
37+
// When a user focuses on or changes any input element, we expect a console message
38+
39+
$('div').on('mouseenter mouseleave', // bind to multiple events
40+
function() {
41+
console.log('mouse hovered over or left a div');
42+
}
43+
);
2044
```
21-
// Event biding using the `$.fn.bind` method
22-
$('p').bind('click', function() {
23-
console.log('click');
45+
46+
#### <a name="multiple-events-multiple-handlers">Many events and handlers</a>
47+
48+
Suppose that instead you want different event handlers for when the mouse enters and
49+
leaves an element. This is more common than the previous example. For example, if you
50+
want to show and hide a tooltip on hover, you would use this.
51+
52+
`.on()` accepts an object containing multiple events and handlers.
53+
54+
```
55+
$('div').on({
56+
mouseenter: function() {
57+
console.log('hovered over a div');
58+
},
59+
mouseleave: function() {
60+
console.log('mouse left a div');
61+
},
62+
click: function() {
63+
console.log('clicked on a div');
64+
}
2465
});
2566
```
67+
68+
#### <a name="event-object">The event object</a>
69+
70+
Handling events can be tricky. It's often helpful to use the extra information contained
71+
in the event object passed to the event handler for more control. To become familiar with
72+
the event object, use this code to inspect it in your browser console after you click on
73+
a `<div>` in the page. For a breakdown of the event object, see
74+
<a href="/events/inside-event-handling-function/">Inside the Event Handling Function</a>.
2675

2776
```
28-
// Event binding using the `$.fn.bind` method with data
29-
$('input').bind(
30-
'click change', // bind to multiple events
31-
{ foo : 'bar' }, // pass in data
32-
function(eventObject) {
33-
console.log(eventObject.type, eventObject.data);
34-
// logs event type, then { foo : 'bar' }
35-
}
36-
);
77+
$('div').on('click', function(event) {
78+
console.log('event object:');
79+
console.dir(event);
80+
});
81+
```
82+
83+
#### <a name="passing-data">Passing data to the event handler</a>
84+
85+
You can pass your own data to the event object.
86+
87+
```
88+
$('p').on('click', {foo: 'bar'}, function(event) {
89+
console.log('event data: ' + event.data.foo + ' (should be "bar")');
90+
});
91+
```
92+
93+
94+
#### <a name="event-delegation">Binding events to elements that don't exist yet</a>
95+
96+
This is called _event delegation_. Here's an example just for completeness, but see the
97+
page on <a href="/events/event-delegation/">Event Delegation</a> for a full explanation.
98+
99+
```
100+
$('ul').on('click', 'li', function() {
101+
console.log('Something in a <ul> was clicked, and we detected that it was an <li> element.
102+
});
37103
```
38104

39105
### Connecting Events to Run Only Once
40106

41107
Sometimes you need a particular handler to run only once — after that, you may
42108
want no handler to run, or you may want a different handler to run. jQuery
43-
provides the `$.fn.one` method for this purpose.
109+
provides the `.one()` method for this purpose.
44110

45111
```
46-
// Switching handlers using the `$.fn.one` method
112+
// Switching handlers using the `.one()` method
47113
$('p').one('click', function() {
48114
console.log('You just clicked this for the first time!');
49115
$(this).click(function() { console.log('You have clicked this before!'); });
50116
});
51117
```
52118

53-
The `$.fn.one` method is especially useful if you need to do some complicated
119+
The `.one()` method is especially useful if you need to do some complicated
54120
setup the first time an element is clicked, but not subsequent times.
55121

122+
`.one()` accepts the same arguments as `on()` which means it supports multiple events to one
123+
or multiple handlers, passing custom data and event delegation.
124+
56125
### Disconnecting Events
57126

58-
To disconnect an event handler, you use the `$.fn.unbind` method and pass in
59-
the event type to unbind. If you attached a named function to the event, then
60-
you can isolate the unbinding to that named function by passing it as the
61-
second argument.
127+
Although all the fun of jQuery occurs in the `.on()` method, it's counterpart is just as important
128+
if you want to be a responsible developer. `.off()` cleans up that event
129+
binding when you don't need it anymore. Complex user interfaces with lots of event bindings
130+
can bog down browser performance, so using the `.off()` method diligently is a best practice to
131+
ensure that you only have the event bindings that you need, when you need them.
62132

63133
```
64134
// Unbinding all click handlers on a selection
65-
$('p').unbind('click');
135+
$('p').off('click');
66136
```
67137

68138
```
69139
// Unbinding a particular click handler, using a reference to the function
70140
var foo = function() { console.log('foo'); };
71141
var bar = function() { console.log('bar'); };
72142
73-
$('p').bind('click', foo).bind('click', bar);
74-
$('p').unbind('click', bar); // foo is still bound to the click event
143+
$('p').on('click', foo).bind('click', bar);
144+
$('p').off('click', bar); // foo is still bound to the click event
75145
```
76146

77147
### Namespacing Events
78148

79149
For complex applications and for plugins you share with others, it can be
80150
useful to namespace your events so you don't unintentionally disconnect events
81-
that you didn't or couldn't know about.
82-
83-
```
84-
// Namespacing events
85-
$('p').bind('click.myNamespace', function() { /* ... */ });
86-
$('p').unbind('click.myNamespace');
87-
$('p').unbind('.myNamespace'); // unbind all events in the namespace
88-
```
89-
90-
### Binding Multiple Events
91-
92-
Quite often elements in your application will be bound to multiple events, each
93-
having a different function for handing the event. In these cases you can pass
94-
an object into `$.fn.bind` with one or more key/value pairs, with the key being
95-
the event name and the value being the function to handle the event.
96-
97-
```
98-
// Binding Multiple Events
99-
$('p').bind({
100-
'click': function() { console.log('clicked!'); },
101-
'mouseover': function() { console.log('hovered!'); }
102-
});
103-
```
151+
that you didn't or couldn't know about. For details, see Event Namespacing.
104152

105-
<div class="note" markdown="1">
106-
The option to pass an object of multiple events and handlers to `$.fn.bind` was
107-
introduced in jQuery 1.4.4.
108-
</div>
153+
<!-- TODO: Link to namespacing -->

0 commit comments

Comments
 (0)