|
1 | 1 | ---
|
2 |
| -title : Connecting Events to Elements |
| 2 | +title : Handling Events |
| 3 | +attribution: David Mazza, jQuery Fundementals |
3 | 4 | level: beginner
|
4 | 5 | ---
|
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'); |
| 6 | +jQuery provides a method `.on()` to |
| 7 | +respond to any event on the selected elements. This is called an _event binding_. |
| 8 | +Although `.on()` isn't the only method provided for event binding, it is a best |
| 9 | +practice to use this for jQuery 1.7+. See history of event binding for more info. |
| 10 | +<!-- TODO: link to history page --> |
| 11 | + |
| 12 | +The on method provides several useful features: |
| 13 | +<ul> |
| 14 | +<li><a href="#simple-event-binding">Bind any event triggered on the selected elements to an event handler</a></li> |
| 15 | +<li><a href="#multiple-events-one-handler">Bind multiple events to one event handler</a></li> |
| 16 | +<li><a href="#multiple-events-multiple-handlers">Bind multiple events and multiple handlers to the selected elements</a></li> |
| 17 | +<li><a href="#event-object">Use details about the event in the event handler</a></li> |
| 18 | +<li><a href="#passing-data">Pass data to the event handler for custom events</a></li> |
| 19 | +<li><a href="#event-delegation">Bind events to elements that will be rendered in the future</a></li> |
| 20 | +</ul> |
| 21 | +### Examples |
| 22 | + |
| 23 | +#### <a name="simple-event-binding">Simple event binding</a> |
| 24 | +``` |
| 25 | +// When any <p> tag is clicked, we expect to see '<p> was clicked' in the console. |
| 26 | +$('p').on('click', function() { |
| 27 | + console.log('<p> was clicked'); |
17 | 28 | });
|
18 | 29 | ```
|
19 | 30 |
|
| 31 | +#### <a name="multiple-events-one-handler">Many events, but only one event handler</a> |
| 32 | + |
| 33 | +Suppose you want to trigger the same event whenever the mouse hovers over or leaves |
| 34 | +the selected elements. The best practice for this is to use "mouseenter mouseleave". |
| 35 | +Note the difference between this and the next example. |
| 36 | + |
| 37 | +``` |
| 38 | +// When a user focuses on or changes any input element, we expect a console message |
| 39 | +
|
| 40 | +$('div').on('mouseenter mouseleave', // bind to multiple events |
| 41 | + function() { |
| 42 | + console.log('mouse hovered over or left a div'); |
| 43 | + } |
| 44 | +); |
20 | 45 | ```
|
21 |
| -// Event biding using the `$.fn.bind` method |
22 |
| -$('p').bind('click', function() { |
23 |
| - console.log('click'); |
| 46 | + |
| 47 | +#### <a name="multiple-events-multiple-handlers">Many events and handlers</a> |
| 48 | + |
| 49 | +Suppose that instead you want different event handlers for when the mouse enters and |
| 50 | +leaves an element. This is more common than the previous example. For example, if you |
| 51 | +want to show and hide a tooltip on hover, you would use this. |
| 52 | + |
| 53 | +`.on()` accepts an object containing multiple events and handlers. |
| 54 | + |
| 55 | +``` |
| 56 | +$('div').on({ |
| 57 | + mouseenter: function() { |
| 58 | + console.log('hovered over a div'); |
| 59 | + }, |
| 60 | + mouseleave: function() { |
| 61 | + console.log('mouse left a div'); |
| 62 | + }, |
| 63 | + click: function() { |
| 64 | + console.log('clicked on a div'); |
| 65 | + } |
24 | 66 | });
|
25 | 67 | ```
|
| 68 | + |
| 69 | +#### <a name="event-object">The event object</a> |
| 70 | + |
| 71 | +Handling events can be tricky. It's often helpful to use the extra information contained |
| 72 | +in the event object passed to the event handler for more control. To become familiar with |
| 73 | +the event object, use this code to inspect it in your browser console after you click on |
| 74 | +a `<div>` in the page. For a breakdown of the event object, see |
| 75 | +<a href="/events/inside-event-handling-function/">Inside the Event Handling Function</a>. |
26 | 76 |
|
27 | 77 | ```
|
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 |
| -); |
| 78 | +$('div').on('click', function(event) { |
| 79 | + console.log('event object:'); |
| 80 | + console.dir(event); |
| 81 | +}); |
| 82 | +``` |
| 83 | + |
| 84 | +#### <a name="passing-data">Passing data to the event handler</a> |
| 85 | + |
| 86 | +You can pass your own data to the event object. |
| 87 | + |
| 88 | +``` |
| 89 | +$('p').on('click', {foo: 'bar'}, function(event) { |
| 90 | + console.log('event data: ' + event.data.foo + ' (should be "bar")'); |
| 91 | +}); |
| 92 | +``` |
| 93 | + |
| 94 | + |
| 95 | +#### <a name="event-delegation">Binding events to elements that don't exist yet</a> |
| 96 | + |
| 97 | +This is called _event delegation_. Here's an example just for completeness, but see the |
| 98 | +page on <a href="/events/event-delegation/">Event Delegation</a> for a full explanation. |
| 99 | + |
| 100 | +``` |
| 101 | +$('ul').on('click', 'li', function() { |
| 102 | + console.log('Something in a <ul> was clicked, and we detected that it was an <li> element. |
| 103 | +}); |
37 | 104 | ```
|
38 | 105 |
|
39 | 106 | ### Connecting Events to Run Only Once
|
40 | 107 |
|
41 | 108 | Sometimes you need a particular handler to run only once — after that, you may
|
42 | 109 | want no handler to run, or you may want a different handler to run. jQuery
|
43 |
| -provides the `$.fn.one` method for this purpose. |
| 110 | +provides the `.one()` method for this purpose. |
44 | 111 |
|
45 | 112 | ```
|
46 |
| -// Switching handlers using the `$.fn.one` method |
| 113 | +// Switching handlers using the `.one()` method |
47 | 114 | $('p').one('click', function() {
|
48 | 115 | console.log('You just clicked this for the first time!');
|
49 | 116 | $(this).click(function() { console.log('You have clicked this before!'); });
|
50 | 117 | });
|
51 | 118 | ```
|
52 | 119 |
|
53 |
| -The `$.fn.one` method is especially useful if you need to do some complicated |
| 120 | +The `.one()` method is especially useful if you need to do some complicated |
54 | 121 | setup the first time an element is clicked, but not subsequent times.
|
55 | 122 |
|
| 123 | +`.one()` accepts the same arguments as `on()` which means it supports multiple events to one |
| 124 | +or multiple handlers, passing custom data and event delegation. |
| 125 | + |
56 | 126 | ### Disconnecting Events
|
57 | 127 |
|
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. |
| 128 | +Although all the fun of jQuery occurs in the `.on()` method, it's counterpart is just as important |
| 129 | +if you want to be a responsible developer. `.off()` cleans up that event |
| 130 | +binding when you don't need it anymore. Complex user interfaces with lots of event bindings |
| 131 | +can bog down browser performance, so using the `.off()` method diligently is a best practice to |
| 132 | +ensure that you only have the event bindings that you need, when you need them. |
62 | 133 |
|
63 | 134 | ```
|
64 | 135 | // Unbinding all click handlers on a selection
|
65 |
| -$('p').unbind('click'); |
| 136 | +$('p').off('click'); |
66 | 137 | ```
|
67 | 138 |
|
68 | 139 | ```
|
69 | 140 | // Unbinding a particular click handler, using a reference to the function
|
70 | 141 | var foo = function() { console.log('foo'); };
|
71 | 142 | var bar = function() { console.log('bar'); };
|
72 | 143 |
|
73 |
| -$('p').bind('click', foo).bind('click', bar); |
74 |
| -$('p').unbind('click', bar); // foo is still bound to the click event |
| 144 | +$('p').on('click', foo).bind('click', bar); |
| 145 | +$('p').off('click', bar); // foo is still bound to the click event |
75 | 146 | ```
|
76 | 147 |
|
77 | 148 | ### Namespacing Events
|
78 | 149 |
|
79 | 150 | For complex applications and for plugins you share with others, it can be
|
80 | 151 | 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 |
| -``` |
| 152 | +that you didn't or couldn't know about. For details, see Event Namespacing. |
104 | 153 |
|
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> |
| 154 | +<!-- TODO: Link to namespacing --> |
0 commit comments