From 9cf941c331e452f708d2ec8c91833e8a350864df Mon Sep 17 00:00:00 2001
From: Markus Amalthea Magnuson
Date: Sun, 3 Mar 2013 21:50:27 +0100
Subject: [PATCH 1/3] Code style fixes.
* Single quotes to double quotes.
* Spaces to tabs.
* Whitespace fixes inside parentheses etc.
* Some empty line insertions and removals.
---
page/events/event-basics.md | 104 ++---
page/events/event-delegation.md | 65 ++-
page/events/event-extensions.md | 84 ++--
page/events/event-helpers.md | 12 +-
page/events/handling-events.md | 64 +--
page/events/history-of-events.md | 58 +--
page/events/inside-event-handling-function.md | 18 +-
page/events/introduction-to-custom-events.md | 424 ++++++++----------
page/events/introduction-to-events.md | 89 ++--
page/events/triggering-event-handlers.md | 31 +-
10 files changed, 431 insertions(+), 518 deletions(-)
diff --git a/page/events/event-basics.md b/page/events/event-basics.md
index 685d390c..dc2d8444 100644
--- a/page/events/event-basics.md
+++ b/page/events/event-basics.md
@@ -24,15 +24,15 @@ 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" );
});
```
@@ -44,16 +44,16 @@ after the event listeners are established will not automatically pick up event b
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);
+$( 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 );
});
```
@@ -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);
+ }
);
```
@@ -121,19 +121,19 @@ the DOM element into a jQuery object that we can use jQuery methods on, we
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" );
+ }
});
```
@@ -145,11 +145,11 @@ 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!" )
+ }
);
```
@@ -159,9 +159,9 @@ 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,9 +173,9 @@ 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
@@ -187,16 +187,16 @@ 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
@@ -207,13 +207,13 @@ 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!" ); } );
}
```
@@ -225,10 +225,10 @@ the first click on *each* paragraph element rather than the function being remov
```
// 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 );
}
```
diff --git a/page/events/event-delegation.md b/page/events/event-delegation.md
index 2391af74..1f79ca4d 100644
--- a/page/events/event-delegation.md
+++ b/page/events/event-delegation.md
@@ -9,25 +9,17 @@ attribution:
Say you have to add new line items to your page, given the following HTML:
```
-
-
+
```
@@ -36,16 +28,16 @@ We need to attach the same event handler to multiple elements. In this example
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:
```
// add a new element on to our existing list
-$("#list").append("
was clicked" );
});
```
@@ -39,8 +39,8 @@ Note the difference between this and the next example.
```
// When a user focuses on or changes any input element, we expect a console message
// bind to multiple events
-$("div").on( "mouseenter mouseleave", function() {
- console.log("mouse hovered over or left a div");
+$( "div" ).on( "mouseenter mouseleave", function() {
+ console.log( "mouse hovered over or left a div" );
});
```
@@ -53,16 +53,16 @@ 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");
- }
+$( "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" );
+ }
});
```
@@ -75,9 +75,9 @@ a `
` in the page. For a breakdown of the event object, see
Inside the Event Handling Function.
```
-$("div").on( "click", function( event ) {
- console.log("event object:");
- console.dir( event );
+$( "div" ).on( "click", function( event ) {
+ console.log( "event object:" );
+ console.dir( event );
});
```
@@ -86,10 +86,10 @@ $("div").on( "click", function( event ) {
You can pass your own data to the event object.
```
-$("p").on( "click", {
- foo: "bar"
+$( "p" ).on( "click", {
+ foo: "bar"
}, function( event ) {
- console.log( "event data: " + event.data.foo + " (should be 'bar')" );
+ console.log( "event data: " + event.data.foo + " (should be 'bar')" );
});
```
@@ -100,8 +100,8 @@ This is called _event delegation_. Here's an example just for completeness, but
page on Event Delegation for a full explanation.
```
-$("ul").on( "click", "li", function() {
- console.log("Something in a
was clicked, and we detected that it was an
element.");
+$( "ul" ).on( "click", "li", function() {
+ console.log( "Something in a
was clicked, and we detected that it was an
element." );
});
```
@@ -113,11 +113,11 @@ provides the `.one()` method for this purpose.
```
// Switching handlers using the `.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!");
- });
+$( "p" ).one( "click", function() {
+ console.log( "You just clicked this for the first time!" );
+ $( this ).click(function() {
+ console.log( "You have clicked this before!" );
+ });
});
```
@@ -137,23 +137,23 @@ ensure that you only have the event bindings that you need, when you need them.
```
// Unbinding all click handlers on a selection
-$("p").off("click");
+$( "p" ).off( "click" );
```
```
// Unbinding a particular click handler, using a reference to the function
var foo = function() {
- console.log("foo");
+ console.log( "foo" );
};
var bar = function() {
- console.log("bar");
+ console.log( "bar" );
};
-$("p").on( "click", foo ).on( "click", bar );
+$( "p" ).on( "click", foo ).on( "click", bar );
// foo will stay bound to the click event
-$("p").off( "click", bar );
+$( "p" ).off( "click", bar );
```
### Namespacing Events
diff --git a/page/events/history-of-events.md b/page/events/history-of-events.md
index 3ebfe1d5..ead1bd94 100644
--- a/page/events/history-of-events.md
+++ b/page/events/history-of-events.md
@@ -8,13 +8,13 @@ Given the following html, for our example we want to log the text of the each `<
```
-
-
Item #1
-
Item #2
-
Item #3
-
...
-
Item #100
-
+
+
Item #1
+
Item #2
+
Item #3
+
...
+
Item #100
+
```
@@ -24,8 +24,8 @@ Introduced in jQuery v1.0
It is possible to use `.bind()` and attach a handler to every element.
```
-$("#list li").bind( "click", function(event) {
- console.log( $elem.text() );
+$( "#list li" ).bind( "click", function( event ) {
+ console.log( $elem.text() );
});
```
As discussed in the [event delegation](/event/event-delegation) article, this is not optimal.
@@ -40,11 +40,11 @@ Introduced in jQuery v1.0
Generally we don't associate `.bind()` with *event delegation*, however prior to jQuery v1.3 it was the only means of delegation available to us.
```
-$("#list").bind( "click", function(event) {
- var $elem = $( event.target );
- if ( $elem.is("li") ){
- console.log( $elem.text() );
- }
+$( "#list" ).bind( "click", function( event ) {
+ var $elem = $( event.target );
+ if ( $elem.is( "li" ) ) {
+ console.log( $elem.text() );
+ }
});
```
We are able to take advantage of *event bubbling* here by attaching a *click* event to the parent `
` element. Whenever the `
` is clicked, the event bubbles up to its parent, the `
`, which executes our event handler. Our event handler checks to see if the **event.target** (the element that caused the event to fire) matches our selector.
@@ -56,9 +56,9 @@ Introduced in jQuery v1.3
All `.live()` event handlers are bound to the *document* root by default.
```
-$("#list li").live( "click", function(event) {
- var $elem = $( this );
- console.log( $elem.text() );
+$( "#list li" ).live( "click", function( event ) {
+ var $elem = $( this );
+ console.log( $elem.text() );
});
```
@@ -81,18 +81,18 @@ Passing the *context* as a second optional argument to the `$()` function has be
If we were take our previous `.live()` example and provide it the default *context*, it would look like:
```
-$( "#list li", document ).live( "click", function(event) {
- var $elem = $( this );
- console.log( $elem.text() );
+$( "#list li", document ).live( "click", function( event ) {
+ var $elem = $( this );
+ console.log( $elem.text() );
});
```
Since we can override the *context* when using the `.live()` method, we can specify a *context* that is closer to the element in the DOM hierarchy
```
-$( "li", "#list" ).live( "click", function(event) {
- var $elem = $( this );
- console.log( $elem.text() );
+$( "li", "#list" ).live( "click", function( event ) {
+ var $elem = $( this );
+ console.log( $elem.text() );
});
```
@@ -104,9 +104,9 @@ First introduced in jQuery v1.4.2
The `.delegate()` method provides a clear difference between the *context* of where to attach delegated event handler, and the *selector* to match when the event bubbles up to the delegated element.
```
-$("#list").delegate( "li", "click", function(event) {
- var $elem = $( this );
- console.log( $elem.text() );
+$( "#list" ).delegate( "li", "click", function( event ) {
+ var $elem = $( this );
+ console.log( $elem.text() );
});
```
@@ -116,9 +116,9 @@ First introduced in jQuery v1.7
The `on.()` method gives us a semantic approach for creating directly bound events as well as delegated events. It eliminates the need to use the deprecated`.bind()`, `.live()` and `.delegate()` methods, providing a single API for creating events.
```
-$("#list").on( "click", "li", function(event) {
- var $elem = $( this );
- console.log( $elem.text() );
+$( "#list" ).on( "click", "li", function( event ) {
+ var $elem = $( this );
+ console.log( $elem.text() );
});
```
diff --git a/page/events/inside-event-handling-function.md b/page/events/inside-event-handling-function.md
index ac57a4e7..5c95fd44 100644
--- a/page/events/inside-event-handling-function.md
+++ b/page/events/inside-event-handling-function.md
@@ -50,17 +50,11 @@ var $this = $( this );
```
// Preventing a link from being followed
-$("a").click(function(e) {
-
- var $this = $( this );
-
- if ( $this.attr("href").match("evil") ) {
-
- e.preventDefault();
-
- $this.addClass("evil");
-
- }
-
+$( "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 0811c310..8855ef22 100644
--- a/page/events/introduction-to-custom-events.md
+++ b/page/events/introduction-to-custom-events.md
@@ -31,10 +31,10 @@ on, and it's controlled by two three-way switches and a clapper:
```
-
-
-
-
+
+
+
+
```
@@ -45,47 +45,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").on( "changeState", function(e) {
-
- var $light = $( this );
-
- if ( $light.hasClass("on") ) {
-
- $light.removeClass("on").addClass("off");
-
- } else {
-
- $light.removeClass("off").addClass("on");
-
- }
-
+$( ".lightbulb" ).on( "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");
-
- });
+$( ".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.
@@ -94,16 +78,16 @@ Let's make our example a little more interesting. We'll add another ro
```
-
-
-
-
+
+
+
+
-
-
-
-
+
+
+
+
```
@@ -115,47 +99,29 @@ 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").on( "changeState", function(e) {
-
- var $light = $( this );
-
- if ($light.hasClass("on")) {
-
- $light.trigger("turnOff");
-
- } else {
-
- $light.trigger("turnOn");
- }
-
-}).on( "turnOn", function(e) {
-
- $( this ).removeClass("off").addClass("on");
-
-}).on( "turnOff", function(e) {
-
- $( this ).removeClass("on").addClass("off");
-
+$( ".lightbulb" ).on( "changeState", function( e ) {
+ var $light = $( this );
+ if ( $light.hasClass( "on" ) ) {
+ $light.trigger( "turnOff" );
+ } else {
+ $light.trigger( "turnOn" );
+ }
+}).on( "turnOn", function( e ) {
+ $( this ).removeClass( "off" ).addClass( "on" );
+}).on( "turnOff", function( e ) {
+ $( this ).removeClass( "on" ).addClass( "off" );
});
-$(".switch, .clapper").click(function() {
-
- $( this ).parent().find(".lightbulb").trigger("changeState");
-
+$( ".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");
-
- }
-
+$( "#master_switch" ).click(function() {
+ if ( $( ".lightbulb.on" ).length ) {
+ $( ".lightbulb" ).trigger( "turnOff" );
+ } else {
+ $( ".lightbulb" ).trigger( "turnOn" );
+ }
});
```
@@ -192,14 +158,14 @@ custom data in both cases:
```
$( document ).on( "myCustomEvent", {
- foo: "bar"
+ foo: "bar"
}, function( event, arg1, arg2 ) {
- console.log( event.data.foo ); // "bar"
- console.log( arg1 ); // "bim"
- console.log( arg2 ); // "baz"
+ console.log( event.data.foo ); // "bar"
+ console.log( arg1 ); // "bim"
+ console.log( arg2 ); // "baz"
});
-$( document ).trigger( "myCustomEvent", [ "bim", "baz" ]);
+$( document ).trigger( "myCustomEvent", [ "bim", "baz" ] );
```
### A Sample Application
@@ -223,15 +189,15 @@ When we're done, it will look like this:
-
-
Search Results for
-
-
+
+
Search Results for
+
+
```
@@ -274,107 +240,104 @@ results container.
```
$.fn.twitterResult = function( settings ) {
- return this.each(function() {
- var $results = $( this );
- var $actions = $.fn.twitterResult.actions = $.fn.twitterResult.actions || $.fn.twitterResult.createActions();
- var $a = $actions.clone().prependTo( $results );
- var term = settings.term;
-
- $results.find("span.search_term").text( term );
- $.each([ "refresh", "populate", "remove", "collapse", "expand" ], function( i, ev ) {
-
- $results.on( 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 ) ] );
- });
-
- });
-
+ return this.each(function() {
+ var $results = $( this );
+ var $actions = $.fn.twitterResult.actions = $.fn.twitterResult.actions || $.fn.twitterResult.createActions();
+ var $a = $actions.clone().prependTo( $results );
+ var term = settings.term;
+
+ $results.find( "span.search_term" ).text( term );
+ $.each([ "refresh", "populate", "remove", "collapse", "expand" ], function( i, ev ) {
+ $results.on( 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
"
- );
+ 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" );
+ }
};
```
@@ -396,38 +359,36 @@ The Twitter container itself will have just two custom events:
Here's how the Twitter container bindings look:
```
-$("#twitter").on( "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;
- }
+$( "#twitter" ).on( "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;
+ }
}).on( "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 ] );
- });
- });
+ 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 ] );
+ });
+ });
});
```
@@ -441,15 +402,14 @@ pass it as we trigger the Twitter container's `getResults` event. Clicking
"Load Trending Terms" will trigger the Twitter container's `getTrends` event:
```
-$("form").submit(function( event ) {
- var term = $("#search_term").val();
- $("#twitter").trigger( "getResults", [ term ] );
-
- event.preventDefault();
+$( "form" ).submit(function( event ) {
+ var term = $( "#search_term" ).val();
+ $( "#twitter" ).trigger( "getResults", [ term ] );
+ event.preventDefault();
});
-$("#get_trends").click(function() {
- $("#twitter").trigger("getTrends");
+$( "#get_trends" ).click(function() {
+ $( "#twitter" ).trigger( "getTrends" );
});
```
@@ -461,15 +421,15 @@ want to verify the removal of individual containers.
```
$.each([ "refresh", "expand", "collapse" ], function( i, ev ) {
- $( "#" + ev ).click( function( e ) {
- $("#twitter div.results").trigger( 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 ] );
- }
+$( "#remove" ).click(function( e ) {
+ if ( confirm( "Remove all results?" ) ) {
+ $( "#twitter div.results" ).trigger( "remove", [ true ] );
+ }
});
```
diff --git a/page/events/introduction-to-events.md b/page/events/introduction-to-events.md
index 455b9867..089e52ab 100644
--- a/page/events/introduction-to-events.md
+++ b/page/events/introduction-to-events.md
@@ -44,24 +44,20 @@ To accomplish the desired task unobtrusively, let's change our HTML a little bit
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.");
+// Event binding using addEventListener
+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.");
-
+// Event binding using a convenience method
+$( "#helloBtn" ).click(function( event ) {
+ alert( "Hello." );
});
```
@@ -70,47 +66,37 @@ The `$("#helloBtn")` code selects the button element using the `$` (aka `jQuery`
There are a number of ways that events can be listened for using jQuery:
```
-//The many ways to bind events with 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.");
-
+$( "#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.");
-
+$( "#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.");
-
+$( "#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.");
-
- }
+$( "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.");
-
+$( "body" ).on( "click", "button", function( event ) {
+ alert( "Hello." );
});
```
@@ -132,14 +118,12 @@ The event bubbling that occurs affords us the ability to add cells via AJAX for
In all of the previous examples, we've been using anonymous functions and specifying an `event` argument within that function. Let's change it up a little bit.
```
-//Binding a named function
+// Binding a named function
function sayHello( event ) {
-
- alert("Hello.");
-
+ 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.
@@ -149,16 +133,15 @@ But what about that `event` argument in the `sayHello` function—what is it and
If the element has default functionality for a specific event (like a link opens a new page, a button in a form submits the form, etc), that default functionality can be cancelled. This is often useful for AJAX requests. When a user clicks on a button to submit a form via AJAX, we'd want to cancel the button/form's default action (to submit it to the form's `action` attribute), and we would instead do an AJAX request to accomplish the same task for a more seamless experience. To do this, we would utilize the event object and call its `preventDefault` method. We can also prevent the event from bubbling up the DOM tree using `stopPropagation` so that parent elements aren't notified of its occurrence (in the case that event delegation is being used).
```
-//Preventing a default action from occurring and stopping the event bubbling
-$("form").on( "submit", function( event ) {
+// Preventing a default action from occurring and stopping the event bubbling
+$( "form" ).on( "submit", function( event ) {
- // Prevent the form's default submission.
- event.preventDefault();
+ // Prevent the form's default submission.
+ event.preventDefault();
- // Prevent event from bubbling up DOM tree, prohibiting delegation
- event.stopPropagation();
+ event.stopPropagation();
- // Make an AJAX request to submit the form data
+ // Make an AJAX request to submit the form data
});
```
@@ -170,16 +153,16 @@ It's also important to note that the event object contains a property called `or
Finally, to inspect the event itself and see all of the data it contains, you should log the event in the browser's console using `console.log`. This will allow you to see all of an event's properties (including the `originalEvent`) which can be really helpful for debugging.
```
-//Logging an event's information
-$("form").on( "submit", function( event ) {
+// Logging an event's information
+$( "form" ).on( "submit", function( event ) {
- // Prevent the form's default submission.
- event.preventDefault();
+ // Prevent the form's default submission.
+ event.preventDefault();
- // Log the event object for inspectin'
- console.log( event );
+ // Log the event object for inspectin'
+ console.log( event );
- // Make an AJAX request to submit the form data
+ // 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 0ef21fc0..c98fbddb 100644
--- a/page/events/triggering-event-handlers.md
+++ b/page/events/triggering-event-handlers.md
@@ -21,10 +21,9 @@ event system that corresponds to these events.
```
Learn jQuery
```
-
```
-//This will not change the current page
-$("a").trigger("click");
+// This will not change the current page
+$( "a" ).trigger( "click" );
```
## How can I mimic a native browser event, if not `.trigger()`?
@@ -35,8 +34,8 @@ Using these two APIs, you can programmatically create an event that behaves exac
The jQuery UI Team created [jquery.simulate.js](https://github.com/eduardolundgren/jquery-simulate/blob/master/jquery.simulate.js) in order to simplify triggering a native browser event for use in their automated testing. Its usage is modeled after jQuery's trigger.
```
-//Triggering a native browser event using the simulate plugin
-$("a").simulate("click");
+// Triggering a native browser event using the simulate plugin
+$( "a" ).simulate( "click" );
```
This will not only trigger the jQuery event handlers, but also follow the link and change the current page.
@@ -62,24 +61,18 @@ call the function itself whenever you want, without the need for
`.trigger()`.
```
-//Triggering an event handler the right way
+// Triggering an event handler the right way
var foo = function( event ) {
-
- if ( event ) {
-
- console.log( event );
-
- } else {
-
- console.log("this didn't come from an event!");
-
- }
-
+ if ( event ) {
+ console.log( event );
+ } else {
+ console.log( "this didn't come from an event!" );
+ }
};
-$("p").on( 'click', foo );
+$( "p" ).on( "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).
From e37c840ee428a80d3870070581bb36a5b7e018a4 Mon Sep 17 00:00:00 2001
From: Markus Amalthea Magnuson
Date: Sun, 3 Mar 2013 22:15:50 +0100
Subject: [PATCH 2/3] Style and typography fixes.
* Remove double-spaces after periods.
* Remove trailing whitespace.
* Curly apostrophes and quotation marks.
* Em dashes.
* Additional inline code markup of function/property names.
* Move footnote style Markdown links to inline style.
* Replace stray .note divs with Markdown.
* Replace HTML list block with Markdown equivalent.
---
page/events.md | 4 +-
page/events/event-basics.md | 58 ++++++------
page/events/event-delegation.md | 20 ++--
page/events/event-extensions.md | 88 +++++++++---------
page/events/event-helpers.md | 14 ++-
page/events/handling-events.md | 49 +++++-----
page/events/history-of-events.md | 23 ++---
page/events/inside-event-handling-function.md | 12 +--
page/events/introduction-to-custom-events.md | 92 +++++++++----------
page/events/introduction-to-events.md | 51 +++++-----
page/events/triggering-event-handlers.md | 27 +++---
11 files changed, 215 insertions(+), 223 deletions(-)
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 dc2d8444..8076cbb6 100644
--- a/page/events/event-basics.md
+++ b/page/events/event-basics.md
@@ -9,15 +9,15 @@ 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.
@@ -38,10 +38,10 @@ $( "p" ).on( "click", function() {
### 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:
+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(){
@@ -57,14 +57,14 @@ $( document ).ready(function(){
});
```
-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
@@ -74,7 +74,7 @@ the page display area (not the entire browser window).
#### type
-The type of the event (e.g. "click").
+The type of the event (e.g. “click”).
#### which
@@ -116,9 +116,9 @@ 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 );
@@ -139,8 +139,8 @@ $( "a" ).click(function( eventObject ) {
### 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`:
```
@@ -153,8 +153,8 @@ $( "input" ).on(
);
```
-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.
```
@@ -168,8 +168,8 @@ $( "p" ).on({
### Namespacing Events
For complex applications and for plugins you share with others, it can be
-useful to namespace your events so you don't unintentionally disconnect events
-that you didn't or couldn't know about.
+useful to namespace your events so you don’t unintentionally disconnect events
+that you didn’t or couldn’t know about.
```
// Namespacing events
@@ -181,7 +181,7 @@ $( "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.
@@ -201,8 +201,8 @@ $( "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
+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
provides the `$.fn.one` method for this purpose.
```
@@ -218,7 +218,7 @@ function firstClick() {
```
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:
@@ -232,6 +232,6 @@ function firstEvent( eventObject ) {
}
```
-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 1f79ca4d..0b5ac55c 100644
--- a/page/events/event-delegation.md
+++ b/page/events/event-delegation.md
@@ -2,7 +2,7 @@
title : Understanding Event Delegation
level: intermediate
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
@@ -23,7 +23,7 @@ Say you have to add new line items to your page, given the following HTML: