|
| 1 | +--- |
| 2 | +title: jQuery Event Basics |
| 3 | +attribution: jQuery Fundamentals |
| 4 | +level: beginner |
| 5 | +--- |
| 6 | + |
| 7 | +## jQuery Event Basics |
| 8 | + |
| 9 | +### Setting Up Event Responses on DOM Elements |
| 10 | + |
| 11 | +jQuery makes it straightforward to set up event-driven responses on page elements. |
| 12 | +These events are often triggered by the end user's interaction with the page, |
| 13 | +such as when text is entered into a form element or the mouse pointer is moved. |
| 14 | +In some cases, such as the page load and unload events, the browser itself will |
| 15 | +trigger the event. |
| 16 | + |
| 17 | +jQuery offers convenience methods for most native browser events. These methods — |
| 18 | +including `$.fn.click`, `$.fn.focus`, `$.fn.blur`, `$.fn.change`, etc. — are shorthand |
| 19 | +for jQuery's `$.fn.on` method. The on method is useful for binding the same handler |
| 20 | +function to multiple events, when you want to provide data to the event hander, |
| 21 | +when you are working with custom events, or when you want to pass an object of |
| 22 | +multiple events and handlers. |
| 23 | + |
| 24 | +``` |
| 25 | +// Event setup using a convenience method |
| 26 | +$('p').click(function() { |
| 27 | + console.log('You clicked a paragraph!'); |
| 28 | +}); |
| 29 | +``` |
| 30 | + |
| 31 | +``` |
| 32 | +// Equivalent event setup using the `$.fn.on` method |
| 33 | +$('p').on('click', function() { |
| 34 | + console.log('click'); |
| 35 | +}); |
| 36 | +``` |
| 37 | + |
| 38 | +### Extending Events to New Page Elements |
| 39 | + |
| 40 | +It is important to note that `$.fn.on` can only create event listeners |
| 41 | +on elements that exist *at the time you set up the listeners*. Similar elements created |
| 42 | +after the event listeners are established will not automatically pick up event behaviors |
| 43 | +you've set up previously. For example: |
| 44 | + |
| 45 | +``` |
| 46 | +$(document).ready(function(){ |
| 47 | + // Sets up click behavior on all button elements with the alert class |
| 48 | + // that exist in the DOM when the instruction was executed |
| 49 | + $('button.alert').on('click', function(){ |
| 50 | + console.log('A button with the alert class was clicked!'); |
| 51 | + }); |
| 52 | + // Now create a new button element with the alert class. This button |
| 53 | + // was created after the click listeners were applied above, so it |
| 54 | + // will not have the same click behavior as its peers |
| 55 | + $('button').addClass('alert').appendTo(document.body); |
| 56 | +}); |
| 57 | +``` |
| 58 | + |
| 59 | +Consult the article on event delegation to see how to use `$.fn.on` so that |
| 60 | +event behaviors will be extended to new elements without having to rebind them. |
| 61 | + |
| 62 | +### Inside the Event Handler Function |
| 63 | + |
| 64 | +Every event handling function receives an event object, which contains many |
| 65 | +properties and methods. The event object is most commonly used to prevent the |
| 66 | +default action of the event via the preventDefault method. However, the event |
| 67 | +object contains a number of other useful properties and methods, including: |
| 68 | + |
| 69 | +#### pageX, pageY |
| 70 | + |
| 71 | +The mouse position at the time the event occurred, relative to the top left corner of |
| 72 | +the page display area (not the entire browser window). |
| 73 | + |
| 74 | +#### type |
| 75 | + |
| 76 | +The type of the event (e.g. "click"). |
| 77 | + |
| 78 | +#### which |
| 79 | + |
| 80 | +The button or key that was pressed. |
| 81 | + |
| 82 | +#### data |
| 83 | + |
| 84 | +Any data that was passed in when the event was bound. For example: |
| 85 | + |
| 86 | +``` |
| 87 | +// Event setup using the `$.fn.on` method with data |
| 88 | +$('input').on( |
| 89 | + 'change', |
| 90 | + {foo : 'bar'}, // associate data with event binding |
| 91 | + function(eventObject) { |
| 92 | + console.log('An input value has changed! ', eventObject.data.foo); |
| 93 | + } |
| 94 | +); |
| 95 | +``` |
| 96 | + |
| 97 | +#### target |
| 98 | + |
| 99 | +The DOM element that initiated the event. |
| 100 | + |
| 101 | +#### namespace |
| 102 | + |
| 103 | +The namespace specified when the event was triggered. |
| 104 | + |
| 105 | +#### timeStamp |
| 106 | + |
| 107 | +The difference in milliseconds between the time the event occurred in the browser and January 1, 1970. |
| 108 | + |
| 109 | +#### preventDefault() |
| 110 | + |
| 111 | +Prevent the default action of the event (e.g. following a link). |
| 112 | + |
| 113 | +#### stopPropagation() |
| 114 | + |
| 115 | +Stop the event from bubbling up to other elements. |
| 116 | + |
| 117 | +In addition to the event object, the event handling function also has access to |
| 118 | +the DOM element that the handler was bound to via the keyword `this`. To turn |
| 119 | +the DOM element into a jQuery object that we can use jQuery methods on, we |
| 120 | +simply do `$(this)`, often following this idiom: |
| 121 | + |
| 122 | +``` |
| 123 | +var $this = $(this); |
| 124 | +``` |
| 125 | + |
| 126 | +A fuller example would be: |
| 127 | + |
| 128 | +``` |
| 129 | +// Preventing a link from being followed |
| 130 | +$('a').click(function(eventObject) { |
| 131 | + var $this = $(this); |
| 132 | + if ($this.attr('href').match(/evil/)) { |
| 133 | + eventObject.preventDefault(); |
| 134 | + $this.addClass('evil'); |
| 135 | + } |
| 136 | +}); |
| 137 | +``` |
| 138 | + |
| 139 | +### Setting Up Multiple Event Responses |
| 140 | + |
| 141 | +Quite often elements in your application will be bound to multiple events. If |
| 142 | +multiple events are to share the same handling function, you can provide the event types |
| 143 | +as a space-separated list to `$.fn.on`: |
| 144 | + |
| 145 | +``` |
| 146 | +// Multiple events, same handler |
| 147 | +$('input').on( |
| 148 | + 'click change', // bind listeners for multiple events |
| 149 | + function() { |
| 150 | + console.log('An input was clicked or changed!') |
| 151 | + } |
| 152 | +); |
| 153 | +``` |
| 154 | + |
| 155 | +When each event has its own handler, you can pass an object into `$.fn.on` with one or |
| 156 | +more key/value pairs, with the key being the event name and the value being the function |
| 157 | +to handle the event. |
| 158 | + |
| 159 | +``` |
| 160 | +// Binding multiple events with different handlers |
| 161 | +$('p').on({ |
| 162 | + 'click': function() { console.log('clicked!'); }, |
| 163 | + 'mouseover': function() { console.log('hovered!'); } |
| 164 | +}); |
| 165 | +``` |
| 166 | + |
| 167 | +### Namespacing Events |
| 168 | + |
| 169 | +For complex applications and for plugins you share with others, it can be |
| 170 | +useful to namespace your events so you don't unintentionally disconnect events |
| 171 | +that you didn't or couldn't know about. |
| 172 | + |
| 173 | +``` |
| 174 | +// Namespacing events |
| 175 | +$('p').on('click.myNamespace', function() { /* ... */ }); |
| 176 | +$('p').off('click.myNamespace'); |
| 177 | +$('p').off('.myNamespace'); // unbind all events in the namespace |
| 178 | +``` |
| 179 | + |
| 180 | +### Tearing Down Event Listeners |
| 181 | + |
| 182 | +To remove an event listener, you use the `$.fn.off` method and pass in |
| 183 | +the event type to off. If you attached a named function to the event, then |
| 184 | +you can isolate the event tear down to just that named function by passing it as the |
| 185 | +second argument. |
| 186 | + |
| 187 | +``` |
| 188 | +// Tearing down all click handlers on a selection |
| 189 | +$('p').off('click'); |
| 190 | +``` |
| 191 | + |
| 192 | +``` |
| 193 | +// Tearing down a particular click handler, using a reference to the function |
| 194 | +var foo = function() { console.log('foo'); }; |
| 195 | +var bar = function() { console.log('bar'); }; |
| 196 | +
|
| 197 | +$('p').on('click', foo).on('click', bar); |
| 198 | +$('p').off('click', bar); // foo is still bound to the click event |
| 199 | +``` |
| 200 | + |
| 201 | +### Setting Up Events to Run Only Once |
| 202 | + |
| 203 | +Sometimes you need a particular handler to run only once — after that, you may |
| 204 | +want no handler to run, or you may want a different handler to run. jQuery |
| 205 | +provides the `$.fn.one` method for this purpose. |
| 206 | + |
| 207 | +``` |
| 208 | +// Switching handlers using the `$.fn.one` method |
| 209 | +$('p').one('click', firstClick); |
| 210 | +
|
| 211 | +function firstClick(){ |
| 212 | + console.log('You just clicked this for the first time!'); |
| 213 | + // Now set up the new handler for subsequent clicks; |
| 214 | + // omit this step if no further click responses are needed |
| 215 | + $(this).click(function() { console.log('You have clicked this before!'); }); |
| 216 | +} |
| 217 | +``` |
| 218 | + |
| 219 | +Note that in the code snippet above, the `firstClick` function will be executed for |
| 220 | +the first click on *each* paragraph element rather than the function being removed from |
| 221 | +*all* paragraphs when *any* paragraph is clicked for the first time. |
| 222 | + |
| 223 | +`$.fn.one` can also be used to bind multiple events: |
| 224 | + |
| 225 | +``` |
| 226 | +// Using $.fn.one to bind several events |
| 227 | +$('input[id]').one('focus mouseover keydown', firstEvent); |
| 228 | +
|
| 229 | +function firstEvent(eventObject){ |
| 230 | + console.log('A ' + eventObject.type + ' event occurred for the first time on the input with id ' + this.id) |
| 231 | +} |
| 232 | +``` |
| 233 | + |
| 234 | +In this case, the `firstEvent` function will be executed once *for each event*. For the snippet above, this means |
| 235 | +that once an input element gains focus, the handler function will still execute for the first keydown event on that |
| 236 | +element. |
0 commit comments