diff --git a/page/events/events-to-elements.md b/page/events/events-to-elements.md index d64afa1b..cc6c25cf 100644 --- a/page/events/events-to-elements.md +++ b/page/events/events-to-elements.md @@ -1,68 +1,139 @@ --- -title : Connecting Events to Elements +title : Handling Events +attribution: David Mazza, jQuery Fundementals level: beginner --- -jQuery offers convenience methods for most common events, and these are the -methods you will see used most often. These methods — including `$.fn.click`, -`$.fn.focus`, `$.fn.blur`, `$.fn.change`, etc. — are shorthand for jQuery's -`$.fn.bind` method. The bind method is useful for binding the same handler -function to multiple events, when you want to provide data to the event hander, -when you are working with custom events, or when you want to pass an object of -multiple events and handlers. - -``` -// Event binding using a convenience method -$('p').click(function() { - console.log('click'); +jQuery provides a method `.on()` to +respond to any event on the selected elements. This is called an _event binding_. +Although `.on()` isn't the only method provided for event binding, it is a best +practice to use this for jQuery 1.7+. See history of event binding for more info. + + +The on method provides several useful features: +
tag is clicked, we expect to see '
was clicked' in the console. +$('p').on('click', function() { + console.log('
was clicked'); }); ``` +#### Many events, but only one event handler + +Suppose you want to trigger the same event whenever the mouse hovers over or leaves +the selected elements. The best practice for this is to use "mouseenter mouseleave". +Note the difference between this and the next example. + +``` +// When a user focuses on or changes any input element, we expect a console message + +$('div').on('mouseenter mouseleave', // bind to multiple events + function() { + console.log('mouse hovered over or left a div'); + } +); ``` -// Event biding using the `$.fn.bind` method -$('p').bind('click', function() { - console.log('click'); + +#### Many events and handlers + +Suppose that instead you want different event handlers for when the mouse enters and +leaves an element. This is more common than the previous example. For example, if you +want to show and hide a tooltip on hover, you would use this. + +`.on()` accepts an object containing multiple events and handlers. + +``` +$('div').on({ + mouseenter: function() { + console.log('hovered over a div'); + }, + mouseleave: function() { + console.log('mouse left a div'); + }, + click: function() { + console.log('clicked on a div'); + } }); ``` + +#### The event object + +Handling events can be tricky. It's often helpful to use the extra information contained +in the event object passed to the event handler for more control. To become familiar with +the event object, use this code to inspect it in your browser console after you click on +a `