From 2cead800b31d8d663dd7f7457350e4ab9485e2bb Mon Sep 17 00:00:00 2001
From: Aaron
Date: Mon, 15 Oct 2012 14:12:31 -0400
Subject: [PATCH] updated formatting
---
page/events/event-delegation.md | 27 +-
page/events/event-extensions.md | 7 +-
page/events/event-helpers.md | 10 +-
page/events/events-to-elements.md | 16 +-
page/events/inside-event-handling-function.md | 16 +-
page/events/introduction-to-custom-events.md | 474 +++++++++---------
page/events/introduction-to-events.md | 106 ++--
page/events/triggering-event-handlers.md | 24 +-
page/events/using_delegate_and_undelegate.md | 145 +++---
page/events/working_with_events_part_1.md | 90 ++--
10 files changed, 457 insertions(+), 458 deletions(-)
diff --git a/page/events/event-delegation.md b/page/events/event-delegation.md
index 079a9d61..9ee1e538 100644
--- a/page/events/event-delegation.md
+++ b/page/events/event-delegation.md
@@ -26,20 +26,19 @@ method is available, and is the preferred method.
```
-//Event delegation using `$.fn.delegate`
-
- $('#myUnorderedList').delegate('li', 'click', function(e) {
- var $myListItem = $(this);
- // ...
- });
+// Event delegation using `$.fn.delegate`
+$('#myUnorderedList').delegate('li', 'click', function(e) {
+ var $myListItem = $(this);
+ // ...
+});
```
```
-//Event delegation using `$.fn.live`
- $('#myUnorderedList li').live('click', function(e) {
- var $myListItem = $(this);
- // ...
- });
+// Event delegation using `$.fn.live`
+$('#myUnorderedList li').live('click', function(e) {
+ var $myListItem = $(this);
+ // ...
+});
```
### Unbinding Delegated Events
@@ -49,7 +48,7 @@ use `$.fn.undelegate` for events connected with `$.fn.delegate`, and `$.fn.die`
for events connected with `$.fn.live`. As with bind, you can optionally pass
in the name of the bound function.
```
-//Unbinding delegated events
- $('#myUnorderedList').undelegate('li', 'click');
- $('#myUnorderedList li').die('click');
+// Unbinding delegated events
+$('#myUnorderedList').undelegate('li', 'click');
+$('#myUnorderedList li').die('click');
```
diff --git a/page/events/event-extensions.md b/page/events/event-extensions.md
index 473ef546..ab0bff92 100644
--- a/page/events/event-extensions.md
+++ b/page/events/event-extensions.md
@@ -94,7 +94,8 @@ When defined, these string properties specify that a special event should be han
The behavior of these properties is easiest to see with an example. Assume a special event defined as follows:
-```jQuery.event.special.pushy = {
+```
+jQuery.event.special.pushy = {
bindType: "click",
delegateType: "click"
};
@@ -112,10 +113,10 @@ So given the special event above, this code shows that a pushy isn't removed by
```
var $p = $("p");
$p.on("click", function( e ) {
- $("body").append("I am a " + e.type + "!"));
+ $("body").append("I am a " + e.type + "!"));
});
$p.on("pushy", function( e ) {
- $("body").append("I am pushy but still a " + e.type + "!");
+ $("body").append("I am pushy but still a " + e.type + "!");
});
$p.trigger("click"); // triggers both handlers
$p.off("click");
diff --git a/page/events/event-helpers.md b/page/events/event-helpers.md
index 69711d57..65db5621 100644
--- a/page/events/event-helpers.md
+++ b/page/events/event-helpers.md
@@ -16,10 +16,10 @@ Prior to jQuery 1.4, the `$.fn.hover` method required two functions.
```
-//The hover helper function
- $('#menu li').hover(function() {
- $(this).toggleClass('hover');
- });
+// The hover helper function
+$('#menu li').hover(function() {
+ $(this).toggleClass('hover');
+});
```
### `$.fn.toggle`
@@ -31,7 +31,7 @@ however, it will accept an unlimited number of functions. Be careful, though:
providing a long list of functions can be difficult to debug.
```
-//The toggle helper function
+// The toggle helper function
$('p.expander').toggle(
function() {
$(this).prev().addClass('open');
diff --git a/page/events/events-to-elements.md b/page/events/events-to-elements.md
index 1127b1f4..2fee928f 100644
--- a/page/events/events-to-elements.md
+++ b/page/events/events-to-elements.md
@@ -11,21 +11,21 @@ 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
+// Event binding using a convenience method
$('p').click(function() {
console.log('click');
});
```
```
-//Event biding using the `$.fn.bind` method
+// Event biding using the `$.fn.bind` method
$('p').bind('click', function() {
console.log('click');
});
```
```
-//Event binding using the `$.fn.bind` method with data
+// Event binding using the `$.fn.bind` method with data
$('input').bind(
'click change', // bind to multiple events
{ foo : 'bar' }, // pass in data
@@ -43,7 +43,7 @@ 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
+// Switching handlers using the `$.fn.one` method
$('p').one('click', function() {
console.log('You just clicked this for the first time!');
$(this).click(function() { console.log('You have clicked this before!'); });
@@ -61,12 +61,12 @@ you can isolate the unbinding to that named function by passing it as the
second argument.
```
-//Unbinding all click handlers on a selection
+// Unbinding all click handlers on a selection
$('p').unbind('click');
```
```
-//Unbinding a particular click handler, using a reference to the function
+// Unbinding a particular click handler, using a reference to the function
var foo = function() { console.log('foo'); };
var bar = function() { console.log('bar'); };
@@ -81,7 +81,7 @@ useful to namespace your events so you don't unintentionally disconnect events
that you didn't or couldn't know about.
```
-//Namespacing events
+// Namespacing events
$('p').bind('click.myNamespace', function() { /* ... */ });
$('p').unbind('click.myNamespace');
$('p').unbind('.myNamespace'); // unbind all events in the namespace
@@ -95,7 +95,7 @@ an object into `$.fn.bind` 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
+// Binding Multiple Events
$('p').bind({
'click': function() { console.log('clicked!'); },
'mouseover': function() { console.log('hovered!'); }
diff --git a/page/events/inside-event-handling-function.md b/page/events/inside-event-handling-function.md
index d57a3f8b..bed9a262 100644
--- a/page/events/inside-event-handling-function.md
+++ b/page/events/inside-event-handling-function.md
@@ -46,12 +46,12 @@ simply do $(this), often following this idiom:
```
```
-//Preventing a link from being followed
- $('a').click(function(e) {
- var $this = $(this);
- if ($this.attr('href').match('evil')) {
- e.preventDefault();
- $this.addClass('evil');
- }
- });
+// Preventing a link from being followed
+$('a').click(function(e) {
+ var $this = $(this);
+ if ($this.attr('href').match('evil')) {
+ e.preventDefault();
+ $this.addClass('evil');
+ }
+});
```
diff --git a/page/events/introduction-to-custom-events.md b/page/events/introduction-to-custom-events.md
index d06431a9..f7161c9d 100644
--- a/page/events/introduction-to-custom-events.md
+++ b/page/events/introduction-to-custom-events.md
@@ -27,12 +27,12 @@ on, and it’s controlled by two three-way switches and a clapper:
```
-
-
-
-
-
-
+
+
+
+
+
+
```
@@ -43,31 +43,31 @@ in; they just want to change the state.
Without custom events, you might write some code like this:
```
- $('.switch, .clapper').click(function() {
- var $light = $(this).parent().find('.lightbulb');
- if ($light.hasClass('on')) {
- $light.removeClass('on').addClass('off');
- } else {
- $light.removeClass('off').addClass('on');
- }
- });
+$('.switch, .clapper').click(function() {
+ var $light = $(this).parent().find('.lightbulb');
+ if ($light.hasClass('on')) {
+ $light.removeClass('on').addClass('off');
+ } else {
+ $light.removeClass('off').addClass('on');
+ }
+});
```
With custom events, your code might look more like this:
```
- $('.lightbulb').bind('changeState', function(e) {
- var $light = $(this);
- if ($light.hasClass('on')) {
- $light.removeClass('on').addClass('off');
- } else {
- $light.removeClass('off').addClass('on');
- }
- });
-
- $('.switch, .clapper').click(function() {
- $(this).parent().find('.lightbulb').trigger('changeState');
- });
+$('.lightbulb').bind('changeState', function(e) {
+ var $light = $(this);
+ if ($light.hasClass('on')) {
+ $light.removeClass('on').addClass('off');
+ } else {
+ $light.removeClass('off').addClass('on');
+ }
+});
+
+ $('.switch, .clapper').click(function() {
+ $(this).parent().find('.lightbulb').trigger('changeState');
+ });
```
This last bit of code is not that exciting, but something important has happened: we’ve moved the behavior of the lightbulb to the lightbulb, and away from the switches and the clapper.
@@ -76,19 +76,19 @@ Let’s make our example a little more interesting. We’ll add another room to
```
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
```
@@ -99,33 +99,33 @@ this, we’ll add two more custom events to the lightbulbs: `turnOn` and
some logic to decide which one the master switch should trigger:
```
- $('.lightbulb')
- .bind('changeState', function(e) {
- var $light = $(this);
- if ($light.hasClass('on')) {
- $light.trigger('turnOff');
- } else {
- $light.trigger('turnOn');
- }
- })
- .bind('turnOn', function(e) {
- $(this).removeClass('off').addClass('on');
- })
- .bind('turnOff', function(e) {
- $(this).removeClass('on').addClass('off');
- });
-
- $('.switch, .clapper').click(function() {
- $(this).parent().find('.lightbulb').trigger('changeState');
- });
-
- $('#master_switch').click(function() {
- if ($('.lightbulb.on').length) {
- $('.lightbulb').trigger('turnOff');
- } else {
- $('.lightbulb').trigger('turnOn');
- }
- });
+$('.lightbulb')
+ .bind('changeState', function(e) {
+ var $light = $(this);
+ if ($light.hasClass('on')) {
+ $light.trigger('turnOff');
+ } else {
+ $light.trigger('turnOn');
+ }
+ })
+ .bind('turnOn', function(e) {
+ $(this).removeClass('off').addClass('on');
+ })
+ .bind('turnOff', function(e) {
+ $(this).removeClass('on').addClass('off');
+ });
+
+$('.switch, .clapper').click(function() {
+ $(this).parent().find('.lightbulb').trigger('changeState');
+});
+
+$('#master_switch').click(function() {
+ if ($('.lightbulb.on').length) {
+ $('.lightbulb').trigger('turnOff');
+ } else {
+ $('.lightbulb').trigger('turnOn');
+ }
+});
```
Note how the behavior of the master switch is attached to the master switch;
@@ -160,13 +160,13 @@ Here is an example of the usage of `$.fn.bind` and `$.fn.trigger` that uses
custom data in both cases:
```
- $(document).bind('myCustomEvent', { foo : 'bar' }, function(e, arg1, arg2) {
- console.log(e.data.foo); // 'bar'
- console.log(arg1); // 'bim'
- console.log(arg2); // 'baz'
- });
+$(document).bind('myCustomEvent', { foo : 'bar' }, function(e, arg1, arg2) {
+ console.log(e.data.foo); // 'bar'
+ console.log(arg1); // 'bim'
+ console.log(arg2); // 'baz'
+});
- $(document).trigger('myCustomEvent', [ 'bim', 'baz' ]);
+$(document).trigger('myCustomEvent', [ 'bim', 'baz' ]);
```
### A Sample Application
@@ -190,15 +190,15 @@ When we’re done, it will look like this:
-
-
Search Results for
-
-
+
+
Search Results for
+
+
```
@@ -240,118 +240,118 @@ class to determine which custom event will be triggered on the corresponding
results container.
```
- $.fn.twitterResult = function(settings) {
- return this.each(function() {
- var $results = $(this),
- $actions = $.fn.twitterResult.actions =
- $.fn.twitterResult.actions ||
- $.fn.twitterResult.createActions(),
- $a = $actions.clone().prependTo($results),
- term = settings.term;
-
- $results.find('span.search_term').text(term);
-
- $.each(
- ['refresh', 'populate', 'remove', 'collapse', 'expand'],
- function(i, ev) {
- $results.bind(
- ev,
- { term : term },
- $.fn.twitterResult.events[ev]
- );
- }
- );
-
- // use the class of each action to figure out
- // which event it will trigger on the results panel
- $a.find('li').click(function() {
- // pass the li that was clicked to the function
- // so it can be manipulated if needed
- $results.trigger($(this).attr('class'), [ $(this) ]);
- });
- });
- };
-
- $.fn.twitterResult.createActions = function() {
- return $('
').append(
- '
Refresh
' +
- '
Remove
' +
- '
Collapse
'
- );
- };
-
- $.fn.twitterResult.events = {
- refresh : function(e) {
- // indicate that the results are refreshing
- var $this = $(this).addClass('refreshing');
-
- $this.find('p.tweet').remove();
- $results.append('
Loading ...
');
-
- // get the twitter data using jsonp
- $.getJSON(
- 'http://search.twitter.com/search.json?q=' +
- escape(e.data.term) + '&rpp=5&callback=?',
- function(json) {
- $this.trigger('populate', [ json ]);
- }
- );
- },
-
- populate : function(e, json) {
- var results = json.results;
- var $this = $(this);
-
- $this.find('p.loading').remove();
-
- $.each(results, function(i,result) {
- var tweet = '
';
+ $this.append(tweet);
+ });
+
+ // indicate that the results
+ // are done refreshing
+ $this.removeClass('refreshing');
+ },
+
+ remove : function(e, force) {
+ if (
+ !force &&
+ !confirm('Remove panel for term ' + e.data.term + '?')
+ ) {
+ return;
+ }
+ $(this).remove();
+
+ // indicate that we no longer
+ // have a panel for the term
+ search_terms[e.data.term] = 0;
+ },
+
+ collapse : function(e) {
+ $(this).find('li.collapse').removeClass('collapse')
+ .addClass('expand').text('Expand');
+
+ $(this).addClass('collapsed');
+ },
+
+ expand : function(e) {
+ $(this).find('li.expand').removeClass('expand')
+ .addClass('collapse').text('Collapse');
+
+ $(this).removeClass('collapsed');
+ }
+};
```
The Twitter container itself will have just two custom events:
@@ -371,37 +371,37 @@ The Twitter container itself will have just two custom events:
Here's how the Twitter container bindings look:
```
- $('#twitter')
- .bind('getResults', function(e, term) {
- // make sure we don't have a box for this term already
- if (!search_terms[term]) {
- var $this = $(this);
- var $template = $this.find('div.template');
-
- // make a copy of the template div
- // and insert it as the first results box
- $results = $template.clone().
- removeClass('template').
- insertBefore($this.find('div:first')).
- twitterResult({
- 'term' : term
- });
-
- // load the content using the "refresh"
- // custom event that we bound to the results container
- $results.trigger('refresh');
- search_terms[term] = 1;
- }
- })
- .bind('getTrends', function(e) {
- var $this = $(this);
- $.getJSON('http://search.twitter.com/trends.json?callback=?', function(json) {
- var trends = json.trends;
- $.each(trends, function(i, trend) {
- $this.trigger('getResults', [ trend.name ]);
- });
- });
+$('#twitter')
+ .bind('getResults', function(e, term) {
+ // make sure we don't have a box for this term already
+ if (!search_terms[term]) {
+ var $this = $(this);
+ var $template = $this.find('div.template');
+
+ // make a copy of the template div
+ // and insert it as the first results box
+ $results = $template.clone().
+ removeClass('template').
+ insertBefore($this.find('div:first')).
+ twitterResult({
+ 'term' : term
+ });
+
+ // load the content using the "refresh"
+ // custom event that we bound to the results container
+ $results.trigger('refresh');
+ search_terms[term] = 1;
+ }
+ })
+ .bind('getTrends', function(e) {
+ var $this = $(this);
+ $.getJSON('http://search.twitter.com/trends.json?callback=?', function(json) {
+ var trends = json.trends;
+ $.each(trends, function(i, trend) {
+ $this.trigger('getResults', [ trend.name ]);
});
+ });
+ });
```
So far, we’ve written a lot of code that does approximately nothing, but that’s
@@ -414,15 +414,15 @@ pass it as we trigger the Twitter container’s `getResults` event. Clicking the
“Load Trending Terms” will trigger the Twitter container’s `getTrends` event:
```
- $('form').submit(function(e) {
- e.preventDefault();
- var term = $('#search_term').val();
- $('#twitter').trigger('getResults', [ term ]);
- });
-
- $('#get_trends').click(function() {
- $('#twitter').trigger('getTrends');
- });
+$('form').submit(function(e) {
+ e.preventDefault();
+ var term = $('#search_term').val();
+ $('#twitter').trigger('getResults', [ term ]);
+});
+
+$('#get_trends').click(function() {
+ $('#twitter').trigger('getTrends');
+});
```
By adding a few buttons with the appropriate IDs, we can make it possible to
@@ -432,15 +432,15 @@ event handler as its second argument, telling the event handler that we don’t
want to verify the removal of individual containers.
```
- $.each(['refresh', 'expand', 'collapse'], function(i, ev) {
- $('#' + ev).click(function(e) { $('#twitter div.results').trigger(ev); });
- });
-
- $('#remove').click(function(e) {
- if (confirm('Remove all results?')) {
- $('#twitter div.results').trigger('remove', [ true ]);
- }
- });
+$.each(['refresh', 'expand', 'collapse'], function(i, ev) {
+ $('#' + ev).click(function(e) { $('#twitter div.results').trigger(ev); });
+});
+
+$('#remove').click(function(e) {
+ if (confirm('Remove all results?')) {
+ $('#twitter div.results').trigger('remove', [ true ]);
+ }
+});
```
### Conclusion
diff --git a/page/events/introduction-to-events.md b/page/events/introduction-to-events.md
index ce3a5d0e..fe93d9b0 100644
--- a/page/events/introduction-to-events.md
+++ b/page/events/introduction-to-events.md
@@ -22,7 +22,7 @@ To specify to the browser what to do when an event occurs, you provide a functio
For instance, to alert a message whenever a user clicks on a button, you might write something like this:
```
-
+
```
The event we want to listen to is specified by the button's `onclick` attribute, and the event handler is the `alert` function which alerts "Hello" to the user. While this works, it's an abysmal way to achieve this functionality for a couple of reasons:
@@ -35,26 +35,26 @@ Utilizing inline event handlers like this can be considered *obtrusive JavaScrip
To accomplish the desired task unobtrusively, let's change our HTML a little bit by removing the `onclick` attribute and replacing it with an `id`, which we'll utilize to "hook onto" the button from within a script file.
```
-
+
```
If we wanted to be informed when a user clicks on that button unobtrusively, we might do something like the following in a separate script file:
```
//Event binding using addEventListener
- var helloBtn = document.getElementById('helloBtn');
- helloBtn.addEventListener('click', function(event) {
- alert('Hello.');
- }, false);
+var helloBtn = document.getElementById('helloBtn');
+helloBtn.addEventListener('click', function(event) {
+ alert('Hello.');
+}, false);
```
Here we're saving a reference to the button element by calling `getElementById` and assigning its return value to a variable. We then call `addEventListener` and provide an event handler function that will be called whenever that event occurs. While there's nothing wrong with this code as it will work fine in modern browsers, it won't fare well in versions of IE prior to IE9. This is because Microsoft chose to implement a different method, `attachEvent`, as opposed to the W3C standard `addEventListener`, and didn't get around to changing it until IE9 was released. For this reason, it's beneficial to utilize jQuery because it abstracts away browser inconsistencies, allowing developers to use a single API for these types of tasks, as seen below.
```
//Event binding using a convenience method
- $('#helloBtn').click(function(event) {
- alert('Hello.');
- });
+$('#helloBtn').click(function(event) {
+ alert('Hello.');
+});
```
The `$('#helloBtn')` code selects the button element using the `$` (aka `jQuery`) function and returns a jQuery object. The jQuery object has a bunch of methods (functions) available to it, one of them named `click`, which resides in the jQuery object's prototype. We call the `click` method on the jQuery object and pass along an anonymous function event handler that's going to be executed when a user clicks the button, alerting "Hello." to the user.
@@ -63,36 +63,36 @@ There are a number of ways that events can be listened for using jQuery:
```
//The many ways to bind events with jQuery
- // Attach an event handler directly to the button using jQuery's
- // shorthand `click` method.
- $('#helloBtn').click(function(event) {
- alert('Hello.');
- });
-
- // Attach an event handler directly the to button using jQuery's
- // `bind` method, passing it an event string of `click`
- $('#helloBtn').bind('click', function(event) {
- alert('Hello.');
- });
-
- // As of jQuery 1.7, attach an event handler directly to the button
- // using jQuery's `on` method.
- $('#helloBtn').on('click', function(event) {
- alert('Hello.');
- });
-
- // As of jQuery 1.7, attach an event handler to the `body` element that
- // is listening for clicks, and will respond whenever *any* button is
- // clicked on the page.
- $('body').on({
- click: function(event) {
- alert('Hello.');
- }, 'button');
-
- // An alternative to the previous example, using slightly different syntax.
- $('body').on('click', 'button', function(event) {
- alert('Hello.');
- });
+// Attach an event handler directly to the button using jQuery's
+// shorthand `click` method.
+$('#helloBtn').click(function(event) {
+ alert('Hello.');
+});
+
+// Attach an event handler directly the to button using jQuery's
+// `bind` method, passing it an event string of `click`
+$('#helloBtn').bind('click', function(event) {
+ alert('Hello.');
+});
+
+// As of jQuery 1.7, attach an event handler directly to the button
+// using jQuery's `on` method.
+$('#helloBtn').on('click', function(event) {
+ alert('Hello.');
+});
+
+// As of jQuery 1.7, attach an event handler to the `body` element that
+// is listening for clicks, and will respond whenever *any* button is
+// clicked on the page.
+$('body').on({
+ click: function(event) {
+ alert('Hello.');
+}, 'button');
+
+// An alternative to the previous example, using slightly different syntax.
+$('body').on('click', 'button', function(event) {
+ alert('Hello.');
+});
```
As of jQuery 1.7, all events are bound via the `on` method, whether you call it directly or whether you use an alias/shortcut method such as `bind` or `click`, which are mapped to the `on` method internally. With this in mind, it's beneficial to use the `on` method because the others are all just syntactic sugar, and utilizing the `on` method is going to result in faster and more consistent code.
@@ -114,11 +114,11 @@ In all of the previous examples, we've been using anonymous functions and specif
```
//Binding a named function
- function sayHello(event) {
- alert('Hello.');
- }
+function sayHello(event) {
+ alert('Hello.');
+}
- $('#helloBtn').on('click', sayHello);
+$('#helloBtn').on('click', sayHello);
```
In this slightly different example, we're defining a function called `sayHello` and then passing that function into the `on` method instead of an anonymous function. So many online examples show anonymous functions used as event handlers, but it's important to realize that you can also pass defined functions as event handlers as well. This is important if different elements or different events should perform the same functionality. This helps to keep your code DRY.
@@ -129,11 +129,11 @@ If the element has default functionality for a specific event (like a link opens
```
//Preventing a default action from occurring and stopping the event bubbling
- $('form').on('submit', function(event) {
- event.preventDefault(); // Prevent the form's default submission.
- event.stopPropagation(); // Prevent event from bubbling up DOM tree, prohibiting delegation
- // Make an AJAX request to submit the form data
- });
+$('form').on('submit', function(event) {
+ event.preventDefault(); // Prevent the form's default submission.
+ event.stopPropagation(); // Prevent event from bubbling up DOM tree, prohibiting delegation
+ // Make an AJAX request to submit the form data
+});
```
When utilizing both `preventDefault` and `stopPropagation` simultaneously, you can instead `return false` to achieve both in a more concise manner, but it's advisable to only `return false` when both are actually necessary and not just for the sake of terseness. A final note on `stopPropagation` is that when using it in delegated events, the soonest that event bubbling can be stopped is when the event reaches the element that is delegating it.
@@ -144,9 +144,9 @@ Finally, to inspect the event itself and see all of the data it contains, you sh
```
//Logging an event's information
- $('form').on('submit', function(event) {
- event.preventDefault(); // Prevent the form's default submission.
- console.log(event); // Log the event object for inspectin'
- // Make an AJAX request to submit the form data
- });
+$('form').on('submit', function(event) {
+ event.preventDefault(); // Prevent the form's default submission.
+ console.log(event); // Log the event object for inspectin'
+ // Make an AJAX request to submit the form data
+});
```
diff --git a/page/events/triggering-event-handlers.md b/page/events/triggering-event-handlers.md
index 904fb4f5..cac1a405 100644
--- a/page/events/triggering-event-handlers.md
+++ b/page/events/triggering-event-handlers.md
@@ -15,12 +15,12 @@ because jQuery stores a reference to that handler when it is originally added. A
such as clicking on a file input box or an anchor tag. This is because, there is no event handler attached using jQuery's event system that coorespond to these events.
```
- Learn jQuery
+Learn jQuery
```
```
//This will not change the current page
- $('a').trigger('click');
+$('a').trigger('click');
```
#### How can I mimic a native browser event, if not .trigger()?
@@ -32,7 +32,7 @@ The jQuery UI Team created [jquery.simulate.js](https://github.com/eduardolundgr
```
//Triggering a native browser event using the simulate plugin
- $('a').simulate('click');
+$('a').simulate('click');
```
This will not only trigger the jQuery event handlers, but also follow the link and change the current page.
@@ -59,17 +59,17 @@ call the function itself whenever you want, without the need for
```
//Triggering an event handler the right way
- var foo = function(e) {
- if (e) {
- console.log(e);
- } else {
- console.log('this didn\'t come from an event!');
- }
- };
+var foo = function(e) {
+ if (e) {
+ console.log(e);
+ } else {
+ console.log('this didn\'t come from an event!');
+ }
+};
- $('p').click(foo);
+$('p').click(foo);
- foo(); // instead of $('p').trigger('click')
+foo(); // instead of $('p').trigger('click')
```
A more complex architecture can built on top of trigger using the [publish-subscribe pattern](http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern) using [jQuery plugins](https://gist.github.com/661855).
diff --git a/page/events/using_delegate_and_undelegate.md b/page/events/using_delegate_and_undelegate.md
index d533f4a3..8159a8bd 100644
--- a/page/events/using_delegate_and_undelegate.md
+++ b/page/events/using_delegate_and_undelegate.md
@@ -9,17 +9,16 @@ source: http://www.learningjquery.com/2010/03/using-delegate-and-undelegat
As some of you have heard, there have been two new methods added in jQuery 1.4.2, [.delegate()](http://api.jquery.com/delegate/) and [.undelegate()](http://api.jquery.com/undelegate/). These methods achieve the same thing as the [.live()](http://api.jquery.com/live/) and [.die()](http://api.jquery.com/die/) methods, they just use a different syntax. For those new to *.live()*, it's a method in jQuery that allows you to attach events to elements that appear in the document as well as elements that will appear in the future. An example would be if you attached a click event via `.live()*`
```
- $('img.photo').live('click', function(){
- lightboxify(this);
- });
+$('img.photo').live('click', function(){
+ lightboxify(this);
+});
```
Then appended some photos via ajax later on:
```
//Appends an image
- // append an image
- $('body').append('');
+$('body').append('');
```
The click event would still apply to that new image without having to re-bind the event. Handy, isn't it?
@@ -27,23 +26,23 @@ The click event would still apply to that new image without having to re-bind th
Not too long ago, the *.live()* method was brought up for discussion for a [few](http://forum.jquery.com/topic/jquery-live-jquery-fn-live-discussion) [reasons](http://paulirish.com/2010/on-jquery-live/). One problem discussed is that *.live()* fails when you try to use it alongside traversals like:
```
- // FAILS
- $('ul').find('li').next().live('click', function(){});
- // FAILS
- $('ul').parent().nextAll().live('click', function(){});
+// FAILS
+$('ul').find('li').next().live('click', function(){});
+// FAILS
+$('ul').parent().nextAll().live('click', function(){});
```
and also when you pass any native DOM elements like:
```
- // FAILS
- $(document.body).live('click', function(){});
+// FAILS
+$(document.body).live('click', function(){});
```
Unfortunately, when you use *.live()*, it has to be at the top of the chain like so:
```
- $('ul li').live('click', function(){})
+$('ul li').live('click', function(){})
```
Because this can be frustrating and confusing for many users who are used to the traversing and chainability that jQuery offers, it sparked a discussion about the syntax for *.live()*. Why does it look like all the other methods, yet does not behave the same? Since changing the syntax would result in a whirlwind of code breakage, the jQuery team decided to introduce *.delegate()* and *.undelegate()* to complement *.live()* and *.die()*. Here's an example of how you would normally use *.live()* and *.die()* and how you can now use *.delegate()* and *.undelegate()*:
@@ -51,29 +50,29 @@ Because this can be frustrating and confusing for many users who are used to the
Old way
```
- // Using .live()
- $("table").each(function(){
- $("td", this).live("hover", function(){
- $(this).toggleClass("hover");
- });
- });
+// Using .live()
+$("table").each(function(){
+ $("td", this).live("hover", function(){
+ $(this).toggleClass("hover");
+ });
+});
- // Using .die()
- $("table").each(function(){
- $("td", this).die("hover");
- });
+// Using .die()
+$("table").each(function(){
+ $("td", this).die("hover");
+});
```
New way
```
- // Using .delegate()
- $("table").delegate("td", "hover", function(){
- $(this).toggleClass("hover");
- });
+// Using .delegate()
+$("table").delegate("td", "hover", function(){
+ $(this).toggleClass("hover");
+});
- // Using .undelegate()
- $("table").undelegate("td", "hover");
+// Using .undelegate()
+$("table").undelegate("td", "hover");
```
The benefit of *delegate()* is that it allows you to specify its context. This way, it ensures that we do not bubble all the way up the DOM tree to capture the target of the element. With the .live() method, it bubbles all the way up the DOM each time unless you set context like so: *$('td', $('table')[0]).live('hover', function(){})*. That just looks ugly.
@@ -81,15 +80,15 @@ The benefit of *delegate()* is that it allows you to specify its context. This w
Some often like to think of *delegate()* like a *bind()* call. The syntax is a little different as you can see below.
```
- // .bind() way
- $('ul li').bind('click', function(e){
- // Do something with bind
- });
+// .bind() way
+$('ul li').bind('click', function(e){
+ // Do something with bind
+});
- // .delegate() way
- $('ul').delegate('li', 'click', function(e){
- // Do something with delegate
- });
+// .delegate() way
+$('ul').delegate('li', 'click', function(e){
+ // Do something with delegate
+});
```
@@ -99,29 +98,29 @@ The gotchas of delegate
While it does behave like *.bind()*, it does not allow you to pass an object map of events like *.bind()* does. Take this *.bind()* method for example:
```
- // This works wonderfully
- $('ul li').bind({
- click: function(e){
- // Something on click
- },
- mouseover: function(e){
- // Something on mouse over
- }
- });
+// This works wonderfully
+$('ul li').bind({
+ click: function(e){
+ // Something on click
+ },
+ mouseover: function(e){
+ // Something on mouse over
+ }
+});
```
An error will be thrown when you try to do:
```
- // FAILS!
- $('ul').delegate('li', {
- click: function(e){
- // Something on click
- },
- mouseover: function(e){
- // Something on mouse over
- }
- });
+// FAILS!
+$('ul').delegate('li', {
+ click: function(e){
+ // Something on click
+ },
+ mouseover: function(e){
+ // Something on mouse over
+ }
+});
```
I'm not sure the reasoning behind not implementing this, but I guess I'm not the only one pondering it.
@@ -131,32 +130,32 @@ Granted, *.bind()* didn't have this feature until jQuery 1.4. But if you'd like
I recommend using Robert Katic's patch above, but of course there are other approaches people can take. For example, you can rig up your own custom object map:
```
- var customObjMap = {
- click : function(e){
- // Something on click
- },
- mouseover : function(e){
- // Something on mouse over
- }
- };
+var customObjMap = {
+ click : function(e){
+ // Something on click
+ },
+ mouseover : function(e){
+ // Something on mouse over
+ }
+};
- $('ol').delegate('li', 'click mouseover', function(e){
- if($.isFunction(customObjMap[e.type])){
- customObjMap[e.type].call(this, e);
- }
- });
+$('ol').delegate('li', 'click mouseover', function(e){
+ if($.isFunction(customObjMap[e.type])){
+ customObjMap[e.type].call(this, e);
+ }
+});
```
Another "gotcha" with both *.delegate()* and *.live()* is that when you add the events *mouseenter* and *mouseleave* to an element, and then check the event type (e.type) in the callback function, it incorrectly displays as *mouseover* and *mouseout*. Using .bind(), on the other hand, it displays as *mouseenter* and *mouseleave* as expected. Here is an example:
```
- $('ol').delegate('li', 'mouseenter', function(e){
- alert(e.type); // outputs mouseover
- });
+$('ol').delegate('li', 'mouseenter', function(e){
+ alert(e.type); // outputs mouseover
+});
- $('ol li').bind('mouseenter', function(e){
- alert(e.type); // outputs mouseenter
- });
+$('ol li').bind('mouseenter', function(e){
+ alert(e.type); // outputs mouseenter
+});
```
diff --git a/page/events/working_with_events_part_1.md b/page/events/working_with_events_part_1.md
index cc02e1f6..30ca82c0 100644
--- a/page/events/working_with_events_part_1.md
+++ b/page/events/working_with_events_part_1.md
@@ -38,11 +38,11 @@ a click handler to it that generates an alert message. In jQuery, we might do
so with the following code:
```
- $(document).ready(function() {
- $('button.alert').click(function() {
- alert('this is an alert message');
- });
- });
+$(document).ready(function() {
+ $('button.alert').click(function() {
+ alert('this is an alert message');
+ });
+});
```
Here we are registering the click handler for the button with a class of
@@ -61,12 +61,12 @@ when clicked.
Now, let's create a new button (if we don't already have a second one) using jQuery code like this:
```
- $('#create-button').click(function() {
- if ( $('button.alert').length <2) {
- $('