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: ```
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 = '' + - '' + - result.from_user + - ': ' + - result.text + - ' ' + - result.created_at + - '' + - '
'; - $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'); +$.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 $('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 = '' + + '' + + result.from_user + + ': ' + + result.text + + ' ' + + result.created_at + + '' + + '
'; + $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('