Permalink
Browse files

Merge pull request #211 from rmurphey/68-other-libs-new-PR

New PR for other libs content
  • Loading branch information...
2 parents be21e32 + c51784d commit 03b556408a23a4b5d59e3651ca1aac697f7ea262 @addyosmani addyosmani committed Dec 31, 2012
Showing with 391 additions and 10 deletions.
  1. +236 −0 page/events/event-basics.md
  2. +155 −10 page/using-jquery-core/avoid-conflicts-other-libraries.md
View
236 page/events/event-basics.md
@@ -0,0 +1,236 @@
+---
+title: jQuery Event Basics
+attribution: jQuery Fundamentals
+level: beginner
+---
+
+## jQuery Event Basics
+
+### 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
+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
+function to multiple events, when you want to provide data to the event hander,
+when you are working with custom events, or when you want to pass an object of
+multiple events and handlers.
+
+```
+// Event setup using a convenience method
+$('p').click(function() {
+ console.log('You clicked a paragraph!');
+});
+```
+
+```
+// Equivalent event setup using the `$.fn.on` method
+$('p').on('click', function() {
+ console.log('click');
+});
+```
+
+### Extending Events to New Page Elements
+
+It is important to note that `$.fn.on` can only create event listeners
+on elements that exist *at the time you set up the listeners*. Similar elements created
+after the event listeners are established will not automatically pick up event behaviors
+you've set up previously. For example:
+
+```
+$(document).ready(function(){
+ // Sets up click behavior on all button elements with the alert class
+ // that exist in the DOM when the instruction was executed
+ $('button.alert').on('click', function(){
+ console.log('A button with the alert class was clicked!');
+ });
+ // Now create a new button element with the alert class. This button
+ // was created after the click listeners were applied above, so it
+ // will not have the same click behavior as its peers
+ $('button').addClass('alert').appendTo(document.body);
+});
+```
+
+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
+object contains a number of other useful properties and methods, including:
+
+#### pageX, pageY
+
+The mouse position at the time the event occurred, relative to the top left corner of
+the page display area (not the entire browser window).
+
+#### type
+
+The type of the event (e.g. "click").
+
+#### which
+
+The button or key that was pressed.
+
+#### data
+
+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);
+ }
+);
+```
+
+#### target
+
+The DOM element that initiated the event.
+
+#### namespace
+
+The namespace specified when the event was triggered.
+
+#### timeStamp
+
+The difference in milliseconds between the time the event occurred in the browser and January 1, 1970.
+
+#### preventDefault()
+
+Prevent the default action of the event (e.g. following a link).
+
+#### stopPropagation()
+
+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 into a jQuery object that we can use jQuery methods on, we
+simply do `$(this)`, often following this idiom:
+
+```
+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');
+ }
+});
+```
+
+### 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
+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!')
+ }
+);
+```
+
+When each event has its own handler, you can pass an object into `$.fn.on` with one or
+more key/value pairs, with the key being the event name and the value being the function
+to handle the event.
+
+```
+// Binding multiple events with different handlers
+$('p').on({
+ 'click': function() { console.log('clicked!'); },
+ 'mouseover': function() { console.log('hovered!'); }
+});
+```
+
+### 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.
+
+```
+// Namespacing events
+$('p').on('click.myNamespace', function() { /* ... */ });
+$('p').off('click.myNamespace');
+$('p').off('.myNamespace'); // unbind all events in the namespace
+```
+
+### Tearing Down Event Listeners
+
+To remove an event listener, you use the `$.fn.off` method and pass in
+the event type to off. If you attached a named function to the event, then
+you can isolate the event tear down to just that named function by passing it as the
+second argument.
+
+```
+// Tearing down all click handlers on a selection
+$('p').off('click');
+```
+
+```
+// Tearing down a particular click handler, using a reference to the function
+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
+```
+
+### 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
+provides the `$.fn.one` method for this purpose.
+
+```
+// Switching handlers using the `$.fn.one` method
+$('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!'); });
+}
+```
+
+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
+*all* paragraphs when *any* paragraph is clicked for the first time.
+
+`$.fn.one` can also be used to bind multiple events:
+
+```
+// Using $.fn.one to bind several events
+$('input[id]').one('focus mouseover keydown', firstEvent);
+
+function firstEvent(eventObject){
+ console.log('A ' + eventObject.type + ' event occurred for the first time on the input with id ' + this.id)
+}
+```
+
+In this case, the `firstEvent` function will be executed once *for each event*. For the snippet above, this means
+that once an input element gains focus, the handler function will still execute for the first keydown event on that
+element.
View
165 page/using-jquery-core/avoid-conflicts-other-libraries.md
@@ -1,39 +1,184 @@
---
title : Avoiding Conflicts with Other Libraries
+attribution: jQuery Fundamentals
level: beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
-If you're using another JavaScript library that uses the `$` variable, you might run into conflicts with jQuery. In order to avoid these conflicts, you need to put jQuery in no-conflict mode immediately after it is loaded onto the page and before you attempt to use jQuery in your page.
-You have the option of assigning a variable name to replace `$` in no-conflict mode:
+The jQuery library and virtually all of its plugins are contained within the
+`jQuery` namespace. As a general rule, global objects are stored inside the
+jQuery namespace as well, so you shouldn't get a clash between jQuery and any
+other library (like prototype.js, MooTools, or YUI).
+
+That said, there is one caveat: *by default, jQuery uses `$` as a shortcut for
+`jQuery`.* Thus, if you are using another JavaScript library that uses the `$`
+variable, you can run into conflicts with jQuery. In order to avoid these
+conflicts, you need to put jQuery in no-conflict mode immediately after it is
+loaded onto the page and before you attempt to use jQuery in your page.
+
+##Putting jQuery into No-Conflict Mode
+
+When you put jQuery into no-conflict mode, you have the option of assigning a
+new variable name to replace the `$` alias.
```
<!-- Putting jQuery into no-conflict mode -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
+ // $j is now an alias to the jQuery function;
+ // creating the new alias is optional
+ var $j = jQuery.noConflict();
+ $j(document).ready(function(){
+ $j("div").hide();
+ });
+
+ // The $ variable now has the prototype meaning,
+ // which is a shortcut for document.getElementById.
+ // mainDiv below is a DOM element, not a jQuery object
+ window.onload = function(){
+ var mainDiv = $('main');
+ }
+</script>
+```
+
+In the code above, the `$` will revert back to its meaning in original library.
+You'll still be able to use the full function name `jQuery` as well as the new
+alias `$j` in the rest of your application. The new alias can be named anything
+you'd like: `jq`, `$J`, `awesomeQuery`, etc.
+
+Finally, if you don't want to define another alternative to the full `jQuery`
+function name (you really like to use `$` and don't care about using the other
+library's `$` method), then there's still another approach you might try:
+simply add the `$` as an argument passed to your `jQuery(document).ready()`
+function. This is most frequently used in the case where you still want the
+benefits of really concise jQuery code, but don't want to cause conflicts with
+other libraries.
+
+```
+<!-- Another way to put jQuery into no-conflict mode -->
+<script src="prototype.js"></script>
+<script src="jquery.js"></script>
+<script>
+
+ jQuery.noConflict();
+ jQuery(document).ready(function($){
+ // You can use the locally-scoped $ in here as an alias to jQuery
+ $("div").hide();
+ });
- var $j = jQuery.noConflict();
+ // The $ variable in the global scope has the prototype.js meaning
+ window.onload = function(){
+ var mainDiv = $('main');
+ }
</script>
+
```
-You can continue to use the standard `$` by wrapping your code in a self-executing anonymous function. This is a standard pattern for plugin authoring, where the author cannot know whether another library will have taken over the `$`. See the [Plugins](/plugins) section for more information about writing plugins.
+This is probably the ideal solution for most of your code, considering that
+there'll be less code that you'll have to change in order to achieve complete
+compatibility.
+
+##Including jQuery Before Other Libraries
+
+The code snippets above rely on jQuery being loaded after prototype.js is
+loaded. If you include jQuery before other libraries, you may use `jQuery` when
+you do some work with jQuery, but the `$` will have the meaning defined in the
+other library. There is no need to relinquish the `$` alias by calling
+`jQuery.noConflict()`.
+
+```
+<!-- Loading jQuery before other libraries -->
+<script src="jquery.js"></script>
+<script src="prototype.js"></script>
+<script>
+
+ // Use full jQuery function name to reference jQuery
+ jQuery(document).ready(function(){
+ jQuery("div").hide();
+ });
+
+ // Use the $ variable as defined in prototype.js
+ window.onload = function() {
+ var mainDiv = $('main');
+ };
+
+</script>
+```
+
+##Summary of Ways to Reference the jQuery Function
+
+Here's a recap of ways you can reference the jQuery function when the presence
+of another library creates a conflict over the use of the `$` variable:
+
+###Create a New Alias
+
+The `jQuery.noConflict()` method returns a reference to the jQuery function, so
+you can capture it in whatever variable you'd like:
+
+```
+<script src="prototype.js"></script>
+<script src="jquery.js"></script>
+<script>
+
+ // Give $ back to prototype.js; create new alias to jQuery
+ var $jq = jQuery.noConflict();
+
+</script>
+```
+
+###Use an Immediately Invoked Function Expression
+
+You can continue to use the standard `$` by wrapping your code in an
+immediately invoked function expression; this is also a standard pattern for
+jQuery plugin authoring, where the author cannot know whether another library
+will have taken over the `$`. See the [Plugins](/plugins) section for more
+information about writing plugins.
```
<!-- Using the $ inside an immediately-invoked function expression -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
+ jQuery.noConflict();
+
+ (function($) {
+ // your jQuery code here, using the $
+ })(jQuery);
+</script>
+```
+
+Note that if you use this technique, you will not be able to use prototype.js
+methods inside the immediately invoked function that expect `$` to be
+prototype.js's `$`.
+
+###Use the Argument That's Passed to the `jQuery(document).ready()` Function
+
+```
+<script src="jquery.js"></script>
+<script src="prototype.js"></script>
+<script>
-jQuery.noConflict();
+ jQuery(document).ready(function($){
+ // your jQuery code here, using $ to refer to jQuery
+ });
-(function($) {
+</script>
+```
- // your code here, using the $
+Or using the more concise syntax for the DOM ready function:
+
+```
+<script src="jquery.js"></script>
+<script src="prototype.js"></script>
+<script>
+
+ jQuery(function($){
+ // your jQuery code here, using the $
+ });
-})( jQuery );
</script>
-```
+```

0 comments on commit 03b5564

Please sign in to comment.