Appendix A. Leftovers: The Top Ten Things (We Didn’t Cover)

image with no caption

Even after all that, there’s still plenty we didn’t get around to. There are lots of other jQuery and JavaScript goodies we didn’t manage to squeeze into the book. It would be unfair not to tell you about them, so you can be more prepared for any other facet of jQuery you might encounter on your travels.

#1. Every single thing in the jQuery library

You probably realize by now that jQuery is a massive library. We tried to cover the main stuff that a person new to jQuery would need. You are now armed with all of this knowledge so you can go and check the rest of the library out.

jQuery methods

.add()
.addClass()
.after()
 jQuery.ajax()
.ajaxComplete()
.ajaxError()
 jQuery.ajaxPrefilter()
.ajaxSend()
 jQuery.ajaxSetup()
.ajaxStart()
.ajaxStop()
.ajaxSuccess()
.andSelf()
.animate()
.append()
.appendTo()
.attr()
.before()
.bind()
.blur()
 jQuery.browser
.change()
.children()
.clearQueue()
.click()
.clone()
.closest()
 jQuery.contains()
.contents()
.context
.css()
 jQuery.cssHooks
.data()
 jQuery.data()
.dblclick()
 deferred.always()
 deferred.done()
 deferred.fail()
 deferred.isRejected()
 deferred.isResolved()
 deferred.pipe()
 deferred.promise()
 deferred.reject()
 deferred.rejectWith()
 deferred.resolve()
 deferred.resolveWith()
 deferred.then()
.delay()
.delegate()
.dequeue()
 jQuery.dequeue()
.detach()
.die()
 jQuery.each()
.each()
.empty()
.end()
.eq()
.error()
 jQuery.error
 event.currentTarget
 event.data
 event.isDefaultPrevented()
 event.
 isImmediatePropagationStopped()
 event.isPropagationStopped()
 event.namespace
 event.pageX
 event.pageY
 event.preventDefault()
 event.relatedTarget
 event.result
 event.stopImmediatePropagation()
 event.stopPropagation()
 event.target
 event.timeStamp
 event.type
 event.which
 jQuery.extend()
.fadeIn()
.fadeOut()
.fadeTo()
.fadeToggle()
.filter()
.find()
.first()
.focus()
.focusin()
.focusout()
 jQuery.fx.interval
 jQuery.fx.off
 jQuery.get()
.get()
 jQuery.getJSON()
 jQuery.getScript()
 jQuery.globalEval()
 jQuery.grep()
.has()
.hasClass()
 jQuery.hasData()
.height()
.hide()
 jQuery.holdReady()
.hover()
.html()
 jQuery.inArray()
.index()
.innerHeight()
.innerWidth()
.insertAfter()
.insertBefore()
.is()
 jQuery.isArray()
 jQuery.isEmptyObject()
 jQuery.isFunction()
 jQuery.isPlainObject()
 jQuery.isWindow()
 jQuery.isXMLDoc()
 jQuery()
.jquery
.keydown()
.keypress()
.keyup()
.last()
.length
.live()
.load()
.load()
 jQuery.makeArray()
.map()
 jQuery.map()
 jQuery.merge()
.mousedown()
.mouseenter()
.mouseleave()
.mousemove()
.mouseout()
.mouseover()
.mouseup()
.next()
.nextAll()
.nextUntil()
 jQuery.noConflict()
 jQuery.noop()
.not()
 jQuery.now()
.offset()
.offsetParent()
.one()
.outerHeight()
.outerWidth()
 jQuery.param()
.parent()
.parents()
.parentsUntil()
 jQuery.parseJSON
 jQuery.parseXML()
.position()
 jQuery.post()
.prepend()
.prependTo()
.prev()
.prevAll()
.prevUntil()
.promise()
.prop()
 jQuery.proxy()
.pushStack()
.queue()
 jQuery.queue()
.ready()
.remove()
.removeAttr()
.removeClass()
.removeData()
 jQuery.removeData()
.removeProp()
.replaceAll()
.replaceWith()
.resize()
.scroll()
.scrollLeft()
.scrollTop()
.select()
.serialize()
.serializeArray()
.show()
.siblings()
.size()
.slice()
.slideDown()
.slideToggle()
.slideUp()
.stop()
 jQuery.sub()
.submit()
 jQuery.support
.text()
.toArray()
.toggle()
.toggle()
.toggleClass()
.trigger()
.triggerHandler()
 jQuery.trim()
 jQuery.type()
.unbind()
.undelegate()
 jQuery.unique()
.unload()
.unwrap()
.val()
 jQuery.when()
.width()
.wrap()
.wrapAll()
.wrapInner()

jQuery selectors

All Selector ("*")
Attribute Contains Prefix Selector
[name|="value"]
Attribute Contains Selector [name*="value"]
Attribute Contains Word Selector [name~="value"]
Attribute Ends With Selector [name$="value"]
Attribute Equals Selector [name="value"]
Attribute Not Equal Selector [name!="value"]
Attribute Starts With Selector [name^="value"]
:animated Selector
:button Selector
:checkbox Selector
:checked Selector
Child Selector ("parent > child")
Class Selector (".class")
:contains() Selector
Descendant Selector ("ancestor descendant")
:disabled Selector
Element Selector ("element")
:empty Selector
:enabled Selector
:eq() Selector
:even Selector
:file Selector
:first-child Selector
:first Selector
:focus selector
:gt() Selector
Has Attribute Selector [name]
:has() Selector
:header Selector
:hidden Selector
ID Selector ("#id")
:image Selector
:input Selector
:last-child Selector
:last Selector
:lt() Selector
Multiple Attribute Selector [name="value"]
[name2="value2"]
Multiple Selector ("selector1, selector2,
selectorN")
Next Adjacent Selector ("prev + next")
Next Siblings Selector ("prev ~ siblings")
:not() Selector
:nth-child() Selector
:odd Selector
:only-child Selector
:parent Selector
:password Selector
:radio Selector
:reset Selector
:selected Selector
:submit Selector
:text Selector
:visible Selector

#2. jQuery CDNs

CDNs (content delivery networks, or content distribution networks) are large networks of servers, designed to store and deliver information—data, software, API code, media files or videos, etc.—making it easily accessible on the Web. Each server in the node contains a copy of the data that is being served out. When these nodes are strategically placed around a network—like the Internet—they can increase the speed of information delivery to many more people consuming this data. Windows Azure and Amazon CloudFront are examples of traditional CDNs.

A number of large enterprises provide hosted copies of jQuery on CDN networks that are available for public use. Below are links to the CDN-hosted copies of jQuery that you may hotlink to.

You can include these in your jQuery applications instead of downloading jQuery every time.

#3. The jQuery namespace: noConflict method

Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery’s case, $ is just an alias for jQuery, so all functionality is available without using $. If we need to use another JavaScript library alongside jQuery, we can return control of $ back to the other library with a call to $.noConflict:

<script type="text/javascript" src="other_lib.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
      $.noConflict();
      //Code that uses other libraries $ can follow here.
</script>

This technique is especially effective in conjunction with the .ready method’s ability to alias the jQuery object, as within a callback passed to .ready we can use $ if we wish without fear of conflicts later:

<script type="text/javascript" src="other_lib.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
       $.noConflict();
       jQuery(document).ready(function($) {
              // Code that uses jQuery's $ can follow here.
       });
       // Code that uses other libraries $ can follow here.
</script>

You’ll only need to use this if you plan to use other JavaScript libraries that use the $ as a reference. You will not need this if you are only using jQuery on your page. Even if you include several plug-ins, you will not need this.

#4. Debugging your jQuery code

It is always useful to debug your code—especially if you’re working on a large-scale project, with many different types of objects, includes, or APIs. Oftentimes, you’ll need to know the content of an object or variable sent back to you, but don’t want to alert it out, or figure out how to get at all the properties of an object.

Enter some debugging plug-ins. These can help you look inside your objects so you can see when their properties change values, or track the changes of a variable over time. You can also see how it evolves throughout your application, or if it ever gets null values unintentionally. This can be very useful when you’re troubleshooting JavaScript or jQuery code.

Two of the debugging plug-ins we’ve found useful when coding in JavaScript and jQuery are Dump and VariableDebugger.

There are several others, and there will be more and more over time, as well as improvements to these. We found these useful, but to look for some more that you might like better, go to the jQuery Plug-ins site (http://plugins.jquery.com/) and search for “debug.”

Of course, for everything else, there’s always the browser tools we’ve been using throughout the book.

#5. Advanced animation: queues

Queues in jQuery are mostly used for animations. You can use them for any purpose you like. They are an array of functions stored on a per-element basis, using jQuery.data. They are first-in-first-out (FIFO). You can add a function to the queue by calling .queue, and you remove (by calling) the functions using .dequeue.

Every element can have one to many queues of functions attached to it by jQuery. In most applications, only one queue (called fx) is used. Queues allow a sequence of actions to be called on an element asynchronously, without halting program execution. The typical example of this is calling multiple animation methods on an element. For example:

$('#my_element').slideUp().fadeIn();

When this statement is executed, the element begins its sliding animation immediately, but the fading transition is placed on the fx queue to be called only once the sliding transition is complete.

The .queue method allows us to directly manipulate this queue of functions. Calling .queue with a callback is particularly useful; it allows us to place a new function at the end of the queue.

This feature is similar to providing a callback function with an animation method, but does not require the callback to be given at the time the animation is performed.

$('#my_element').slideUp();
$('#my_element').queue(function() {
      alert('Animation complete.'),
      $(this).dequeue();
});

This is equivalent to:

$('#my_element').slideUp(function() {
      alert('Animation complete.'),
});

Note that when adding a function with .queue, we should ensure that .dequeue is eventually called so that the next function in line executes.

In jQuery 1.4, the function that’s called is passed in another function, as the first argument, that when called automatically dequeues the next item and keeps the queue moving. You would use it like so:

$("#test").queue(function(next) {
      // Do some stuff...
      next();
});

The default queue in jQuery is fx. It is used by .animate and all functions that call it by default.

NOTE: If you are using a custom queue, you must manually .dequeue the functions—they will not autostart like the default fx queue!

#6. Form validation

One very important feature we didn’t have room for is form validation, on the client/browser side, using jQuery. In Chapter 9, Chapter 10, and Chapter 11, we saw a small piece of server-side validation, using PHP, before our data was inserted into our databases. This is also very important, and strongly advised. A malformed insert or select statement to your database could end up revealing much more about your data than you intended.

But back to the client-side validation...

There are many jQuery plug-ins dedicated to form validation. One of our favorites is the aptly named “validation” plug-in, found here: http://docs.jquery.com/Plugins/validation.

This plug-in will allow you to create a series of rules for each element on your form, so you can customize the validation, and refine the data you want to accept in your form. This includes everything from minimum or maximum field lengths, check for required fields, check if a valid email address is entered, and more. Here’s some examples from the jQuery website:

Specifies a name element as required and an email element as required (using the shortcut for a single rule) and a valid email address (using another object literal).

$(".selector").validate({
      rules: {
            // simple rule, converted to {required:true}
            name: "required",
            // compound rule
            email: {
                  required: true,
                  email: true
            }
      }
});

Adds required and a minlength of 2 to an element and specifies custom messages for both.

$("#myinput").rules("add", {
      required: true,
      minlength: 2,
      messages: {
            required: "Required input",
            minlength: jQuery.format("Please, at least {0} characters
are necessary")
      }
});

#7. jQuery UI effects

The jQuery UI Effects library comes with some extra animations, not available in the regular jQuery library. These can be broken down into three separate types of functionality:

  1. Color animations

    Color animations extend the animate function to be able to animate colors as well. It’s heavily used by the class transition feature, and it’s able to color-animate the following properties:

    backgroundColor
    borderBottomColor
    borderLeftColor
    borderRightColor
    borderTopColor
    color
    outlineColor
  2. Class transitions

    Class transitions extend the base class API to be able to animate between two different classes. The following jQuery methods are modified by jQuery UI to accept three additional parameters: speed, easing (optional), and callback.

    • addClass(class)

      • Adds the specified class(es) to each set of matched elements.

    • removeClass(class)

      • Removes all or the specified class(es) from the set of matched elements.

    • toggleClass(class)

      • Adds the specified class if it is not present; removes the specified class if it is present.

    • switchClass(currentClass, newClass)

      • Allows you to visually transition from one class to another.

  3. Advanced easing

    Advanced easing is included in the Effects core, and is a jQuery port of the easing functions written by Robert Penners, which were originally written in ActionScript for Flash. They are a series of mathematical equations designed to make the animation of objects smoother and more accurate. Here’s a list of all the easing functions:

    linear
    swing
    jswing
    easeInQuad
    easeOutQuad
    easeInOutQuad
    easeInCubic
    easeOutCubic
    easeInOutCubic
    easeInQuart
    easeOutQuart
    easeInOutQuart
    easeInQuint
    easeOutQuint
    easeInOutQuint
    easeInSine
    easeOutSine
    easeInOutSine
    easeInExpo
    easeOutExpo
    easeInOutExpo
    easeInCirc
    easeOutCirc
    easeInOutCirc
    easeInElastic
    easeOutElastic
    easeInOutElastic
    easeInBack
    easeOutBack
    easeInOutBack
    easeInBounce
    easeOutBounce
    easeInOutBounce

#8. Creating your own jQuery plug-ins

Extending jQuery with plug-ins and methods is very powerful and can save you and your peers a lot of development time by abstracting your most clever functions into plug-ins.

Rather than writing a whole bunch of text about how to create a jQuery plug-in, we think it’s best left to the experts over at jQuery. They have a very substantial and informative tutorial here: http://docs.jquery.com/Plugins/Authoring.

Here’s a brief summary of what to keep in mind when developing your next jQuery plug-in:

  • Always wrap your plug-in in (function( $ ){ // plugin goes here })( jQuery );.

  • Don’t redundantly wrap the this keyword in the immediate scope of your plug-in’s function.

  • Unless you’re returning an intrinsic value from your plug-in, always have your plug-in’s function return the this keyword to maintain chainability.

  • Rather than requiring a lengthy amount of arguments, pass your plug-in settings in an object literal that can be extended over the plug-in’s defaults.

  • Don’t clutter the jQuery.fn object with more than one namespace per plug-in.

  • Always namespace your methods, events, and data.

  • jQuery.fn is pronounced “jQuery effin.”

#9. Advanced JavaScript: closures

Closures are a very complex topic within JavaScript, and were quite close to making it into the book proper. Although they didn’t, we feel strongly about you needing to know about them, so we wanted to mention them here.

Closures are not hard to understand once you grasp the core concept. However, if you read some of the more detailed, technical descriptions, you might get very confused.

First, a definition (or two):

  • A closure is the local variable for a function, kept alive after the function has returned.

  • Whenever you see the function keyword within another function, the inner function has access to variables in the outer function.

Crazy, right?

Closures fully rely on the scope of variables and objects. The scope refers to where objects, variables, and functions are created and accessible, and in what context they are being called. Basically, objects, variables, and functions can be defined in either a local or global scope.

Local scope: The local scope is when something is defined and accessible only in a certain part of the code, like inside a function.

Global scope: As opposed to the local scope, when something is global is accessible from anywhere in your code.

Consider the following code:

function func1(x) {
      var tmp  = 3;
      function func2(y) {
            alert(x + y + (++tmp));
      }
      func2(10);
}
func1(2);

The tmp variable is declared in local scope, inside the func1 function. This will always alert 16, because func2 can access the x (which was defined as an argument to func1), and it can also access tmp from func1.

That is not a closure. A closure is when you return the inner function. The inner function will close over the variables of func1 before leaving.

Now consider:

function func1(x) {
      var tmp  = 3;
      return function (y) {
            alert(x + y + (++tmp));
      }
}
var func2 = func1(2);  // func2 is now a closure.
func2(10);

Again, tmp is in the local scope, but the func2 function is in the global scope. The above function will also alert 16, because func2 can still refer to x and tmp, even though it is no longer directly inside the scope.

However, since tmp is still hanging around inside func2’s closure, it is also being incremented. It will be incremented each time you call func2.

It is possible to create more than one closure function, either by returning a list of them or by setting them to global variables. All of these will refer to the same x and the same tmp; they don’t make their own copies.

#10. Templates

jQuery templates are still in beta, but are a cool, upcoming feature that might help you build a more flexible site, without much HTML or jQuery. They are designed to take data and bind it to some template markup, so you can consistently use the same markup to display similarly related data.

Check them out here: http://api.jquery.com/category/plugins/templates/.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.163.197