diff --git a/page/events.md b/page/events.md index 665f501c..1fffebe9 100644 --- a/page/events.md +++ b/page/events.md @@ -7,10 +7,10 @@ customFields: value: "tasks" --- jQuery provides simple methods for attaching event handlers to selections. -When an event occurs, the provided function is executed. Inside the function, +When an event occurs, the provided function is executed. Inside the function, `this` refers to the element that was clicked. -For details on jQuery events, visit the +For details on jQuery events, visit the [Events documentation on api.jquery.com](http://api.jquery.com/category/events/). The event handling function can receive an event object. This object can be diff --git a/page/events/event-basics.md b/page/events/event-basics.md index 685d390c..a9485f8d 100644 --- a/page/events/event-basics.md +++ b/page/events/event-basics.md @@ -9,62 +9,62 @@ level: beginner ### Setting Up Event Responses on DOM Elements -jQuery makes it straightforward to set up event-driven responses on page elements. -These events are often triggered by the end user's interaction with the page, -such as when text is entered into a form element or the mouse pointer is moved. -In some cases, such as the page load and unload events, the browser itself will +jQuery makes it straightforward to set up event-driven responses on page elements. +These events are often triggered by the end user's interaction with the page, +such as when text is entered into a form element or the mouse pointer is moved. +In some cases, such as the page load and unload events, the browser itself will trigger the event. -jQuery offers convenience methods for most native browser events. These methods — -including `$.fn.click`, `$.fn.focus`, `$.fn.blur`, `$.fn.change`, etc. — are shorthand -for jQuery's `$.fn.on` method. The on method is useful for binding the same handler +jQuery offers convenience methods for most native browser events. These methods — +including `$.fn.click`, `$.fn.focus`, `$.fn.blur`, `$.fn.change`, etc. — are shorthand +for jQuery's `$.fn.on` method. The `on` 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 setup using a convenience method -$('p').click(function() { - console.log('You clicked a paragraph!'); +$( "p" ).click(function() { + console.log( "You clicked a paragraph!" ); }); ``` ``` // Equivalent event setup using the `$.fn.on` method -$('p').on('click', function() { - console.log('click'); +$( "p" ).on( "click", function() { + console.log( "click" ); }); ``` ### Extending Events to New Page Elements -It is important to note that `$.fn.on` can only create event listeners -on elements that exist *at the time you set up the listeners*. Similar elements created -after the event listeners are established will not automatically pick up event behaviors -you've set up previously. For example: - -``` -$(document).ready(function(){ - // Sets up click behavior on all button elements with the alert class - // that exist in the DOM when the instruction was executed - $('button.alert').on('click', function(){ - console.log('A button with the alert class was clicked!'); - }); - // Now create a new button element with the alert class. This button - // was created after the click listeners were applied above, so it - // will not have the same click behavior as its peers - $('button').addClass('alert').appendTo(document.body); +It is important to note that `$.fn.on` can only create event listeners +on elements that exist *at the time you set up the listeners*. Similar elements created +after the event listeners are established will not automatically pick up event behaviors +you've set up previously. For example: + +``` +$( document ).ready(function(){ + // Sets up click behavior on all button elements with the alert class + // that exist in the DOM when the instruction was executed + $( "button.alert" ).on( "click", function() { + console.log( "A button with the alert class was clicked!" ); + }); + // Now create a new button element with the alert class. This button + // was created after the click listeners were applied above, so it + // will not have the same click behavior as its peers + $( "button" ).addClass( "alert" ).appendTo( document.body ); }); ``` -Consult the article on event delegation to see how to use `$.fn.on` so that +Consult the article on event delegation to see how to use `$.fn.on` so that event behaviors will be extended to new elements without having to rebind them. ### Inside the Event Handler Function Every event handling function receives an event object, which contains many -properties and methods. The event object is most commonly used to prevent the -default action of the event via the preventDefault method. However, the event +properties and methods. The event object is most commonly used to prevent the +default action of the event via the `.preventDefault()` method. However, the event object contains a number of other useful properties and methods, including: #### pageX, pageY @@ -86,12 +86,12 @@ Any data that was passed in when the event was bound. For example: ``` // Event setup using the `$.fn.on` method with data -$('input').on( - 'change', - {foo : 'bar'}, // associate data with event binding - function(eventObject) { - console.log('An input value has changed! ', eventObject.data.foo); - } +$( "input" ).on( + "change", + { foo: "bar" }, // associate data with event binding + function( eventObject ) { + console.log("An input value has changed! ", eventObject.data.foo); + } ); ``` @@ -116,52 +116,52 @@ Prevent the default action of the event (e.g. following a link). Stop the event from bubbling up to other elements. In addition to the event object, the event handling function also has access to -the DOM element that the handler was bound to via the keyword `this`. To turn +the DOM element that the handler was bound to via the keyword `this`. To turn the DOM element into a jQuery object that we can use jQuery methods on, we -simply do `$(this)`, often following this idiom: +simply do `$( this )`, often following this idiom: ``` -var $this = $(this); +var $this = $( this ); ``` A fuller example would be: ``` // Preventing a link from being followed -$('a').click(function(eventObject) { - var $this = $(this); - if ($this.attr('href').match(/evil/)) { - eventObject.preventDefault(); - $this.addClass('evil'); - } +$( "a" ).click(function( eventObject ) { + var $this = $( this ); + if ( $this.attr( "href" ).match( /evil/ ) ) { + eventObject.preventDefault(); + $this.addClass( "evil" ); + } }); ``` ### Setting Up Multiple Event Responses -Quite often elements in your application will be bound to multiple events. If -multiple events are to share the same handling function, you can provide the event types +Quite often elements in your application will be bound to multiple events. If +multiple events are to share the same handling function, you can provide the event types as a space-separated list to `$.fn.on`: ``` // Multiple events, same handler -$('input').on( - 'click change', // bind listeners for multiple events - function() { - console.log('An input was clicked or changed!') - } +$( "input" ).on( + "click change", // bind listeners for multiple events + function() { + console.log( "An input was clicked or changed!" ) + } ); ``` -When each event has its own handler, you can pass an object into `$.fn.on` with one or -more key/value pairs, with the key being the event name and the value being the function +When each event has its own handler, you can pass an object into `$.fn.on` with one or +more key/value pairs, with the key being the event name and the value being the function to handle the event. ``` // Binding multiple events with different handlers -$('p').on({ - 'click': function() { console.log('clicked!'); }, - 'mouseover': function() { console.log('hovered!'); } +$( "p" ).on({ + "click": function() { console.log( "clicked!" ); }, + "mouseover": function() { console.log( "hovered!" ); } }); ``` @@ -173,65 +173,65 @@ that you didn't or couldn't know about. ``` // Namespacing events -$('p').on('click.myNamespace', function() { /* ... */ }); -$('p').off('click.myNamespace'); -$('p').off('.myNamespace'); // unbind all events in the namespace +$( "p" ).on( "click.myNamespace", function() { /* ... */ } ); +$( "p" ).off( "click.myNamespace" ); +$( "p" ).off( ".myNamespace" ); // unbind all events in the namespace ``` ### Tearing Down Event Listeners To remove an event listener, you use the `$.fn.off` method and pass in -the event type to off. If you attached a named function to the event, then +the event type to off. If you attached a named function to the event, then you can isolate the event tear down to just that named function by passing it as the second argument. ``` // Tearing down all click handlers on a selection -$('p').off('click'); +$( "p" ).off( "click" ); ``` ``` // Tearing down a particular click handler, using a reference to the function -var foo = function() { console.log('foo'); }; -var bar = function() { console.log('bar'); }; +var foo = function() { console.log( "foo" ); }; +var bar = function() { console.log( "bar" ); }; -$('p').on('click', foo).on('click', bar); -$('p').off('click', bar); // foo is still bound to the click event +$( "p" ).on( "click", foo ).on( "click", bar ); +$( "p" ).off( "click", bar ); // foo is still bound to the click event ``` ### Setting Up Events to Run Only Once Sometimes you need a particular handler to run only once — after that, you may -want no handler to run, or you may want a different handler to run. jQuery +want no handler to run, or you may want a different handler to run. jQuery provides the `$.fn.one` method for this purpose. ``` // Switching handlers using the `$.fn.one` method -$('p').one('click', firstClick); +$( "p" ).one( "click", firstClick ); -function firstClick(){ - console.log('You just clicked this for the first time!'); - // Now set up the new handler for subsequent clicks; - // omit this step if no further click responses are needed - $(this).click(function() { console.log('You have clicked this before!'); }); +function firstClick() { + console.log( "You just clicked this for the first time!" ); + // Now set up the new handler for subsequent clicks; + // omit this step if no further click responses are needed + $( this ).click( function() { console.log( "You have clicked this before!" ); } ); } ``` Note that in the code snippet above, the `firstClick` function will be executed for -the first click on *each* paragraph element rather than the function being removed from +the first click on *each* paragraph element rather than the function being removed from *all* paragraphs when *any* paragraph is clicked for the first time. `$.fn.one` can also be used to bind multiple events: ``` // Using $.fn.one to bind several events -$('input[id]').one('focus mouseover keydown', firstEvent); +$( "input[id]" ).one( "focus mouseover keydown", firstEvent); -function firstEvent(eventObject){ - console.log('A ' + eventObject.type + ' event occurred for the first time on the input with id ' + this.id) +function firstEvent( eventObject ) { + console.log( "A " + eventObject.type + " event occurred for the first time on the input with id " + this.id ); } ``` -In this case, the `firstEvent` function will be executed once *for each event*. For the snippet above, this means -that once an input element gains focus, the handler function will still execute for the first keydown event on that +In this case, the `firstEvent` function will be executed once *for each event*. For the snippet above, this means +that once an input element gains focus, the handler function will still execute for the first keydown event on that element. diff --git a/page/events/event-delegation.md b/page/events/event-delegation.md index 2391af74..dd27e268 100644 --- a/page/events/event-delegation.md +++ b/page/events/event-delegation.md @@ -2,55 +2,47 @@ title : Understanding Event Delegation level: intermediate source: http://jqfundamentals.com/legacy -attribution: +attribution: - jQuery Fundamentals --- Say you have to add new line items to your page, given the following HTML: ``` - -
- -
- + +
+ +
+ ``` -We need to attach the same event handler to multiple elements. In this example we want to attach an event that will log the text of the anchor tag to the console whenever it is clicked. +We need to attach the same event handler to multiple elements. In this example we want to attach an event that will log the text of the anchor tag to the console whenever it is clicked. We can attach a direct bind click event to each `
  • ` using the `.on()` method, that will alert the text inside of it by doing the following: ``` // attach a directly bound event -$("#list a").on( "click", function( event ) { - event.preventDefault(); - console.log( $( this ).text() ); +$( "#list a" ).on( "click", function( event ) { + event.preventDefault(); + console.log( $( this ).text() ); }); ``` -While this works perfectly fine, there are drawbacks. Consider this: +While this works perfectly fine, there are drawbacks. Consider this: ``` // add a new element on to our existing list -$("#list").append("
  • Item #101
  • "); +$( "#list" ).append( "
  • Item #101
  • " ); ``` -If we were to click our newly added item, nothing would happen. This is because of the directly bound event that we attached previously. Direct events are only attached to elements at the time we called the `.on()` method for our existing collection of ``"s, that is only the ``"s that were found when we call `$()` +If we were to click our newly added item, nothing would happen. This is because of the directly bound event that we attached previously. Direct events are only attached to elements at the time we called the `.on()` method for our existing collection of ``'s, that is only the ``'s that were found when we call `$()`. ## Event Propagation -Understanding how events propagate is an important factor in being able to leverage Event Delegation. Any time an anchor tags is clicked, a *click* event is fired for the: +Understanding how events propagate is an important factor in being able to leverage Event Delegation. Any time an anchor tags is clicked, a *click* event is fired for the: * `` * `
  • ` @@ -60,44 +52,37 @@ Understanding how events propagate is an important factor in being able to lever * `` * *document* root -Anytime one of these links is clicked you can think of it as if you were clicking the entire document body. This is called *event bubbling* or *event propagation*. +Anytime one of these links is clicked you can think of it as if you were clicking the entire document body. This is called *event bubbling* or *event propagation*. Since we know how events bubble we can created a delegated event that listens for a specific event to happen on our element ``` // attach a delegated event -$("#list").on( "click", "a", function( event ) { - event.preventDefault(); - console.log( $( this ).text() ); +$( "#list" ).on( "click", "a", function( event ) { + event.preventDefault(); + console.log( $( this ).text() ); }); ``` -Notice for the second parameter to the `.on()` method we are telling it which selector to listen for. Now when a *click* event is triggered on our `