Easy JavaScript Object Context Switching with jQuery.proxy()

jQuery

JavaScript LogoA popular saying in the Real Estate business is: “Location, location, location!” Well, in JavaScript, it’s all about “context”. When you want to leverage the very powerful keyword: “this”, then understanding the current context is critical.

So, those experienced with native JavaScript should be comfortable with the concept of context (If you are not, take a moment to brush up on this subject; it’s important.) When you need to specify context, you would normally use the .call() or .apply() methods. The jQuery folks have also provided a way to accomplish this with their .proxy() method. This method takes two arguments, which are: the function to be executed and the object whose context should be targeted. Any additional arguments are optional and are passed to the function that is executed.

Example # 1

In Example # 1, we have created two simple objects: “foo” and “bar”. Note that each object has one property named “music”. Next, we set up two click event handlers. In each case, we execute the “handler” function. And that function makes reference to “this”. If we were to run that function by itself, the output of the alert would be “undefined”, because when doing that, “this” refers to the window object, which at this time has no property named “music”.

So, by using the jQuery.proxy() method, we specify the context within which the “handler” function should be executed.

Here is the JS Fiddle link for Example # 1: http://jsfiddle.net/Shm47/

Example # 2

In Example # 2, we have taken our cause to the DOM. We first create a function named toggleColor, which when passed a class name, will toggle that class name.

Next, we set up two click event handlers. In each case, we leverage jQuery.proxy(), to call the “toggleColor” function, and specify the context within which it should run. We’re also specifying the class name to be passed to that function.

Here is the JS Fiddle link for Example # 2: http://jsfiddle.net/WzDUj/

Summary

In this article, we learned about the jQuery.proxy() method. In doing so, we discussed how it is used to specify the context within which a function should be executed. First we demonstrated how you can leverage this function using object literals. We then showed how you can do so by using DOM elements.

Helpful Links for the jQuery.proxy() method

http://api.jquery.com/jQuery.proxy/
http://stackoverflow.com/questions/3349380/jquery-proxy-usage
http://stackoverflow.com/questions/4986329/understanding-proxy-in-jquery
http://blog.kevinchisholm.com/javascript/context-http://blog.kevinchisholm.com/javascript/difference-between-scope-and-context/object-literals/
http://blog.kevinchisholm.com/javascript/difference-between-scope-and-context/

Complex Multiple Script Loading Using the jQuery.when() Method and the jQuery.Deferred Object — Part II

jQuery

jQuery LogoWhat happens when your JavaScript code depends on not only multiple asynchronous scripts, but also one or more JSONP calls? Once again, jQuery.Deferred() and jQuery.when() save the day.

In Part I of this article: “Complex Multiple Script Loading Using the jQuery.when() Method and the jQuery.Deferred Object Part I“, we discussed the complex nature of multiple asynchronous dependencies. In that article, we were able to count on jQuery.when() to pay attention to the resolution of our jQuery.Deferred objects. In this second part, we’ll complicate things even further by adding a JSONP dependency. The “complication” is the fact that the success of the JSONP call requires us to re-think how we will leverage our jQuery.Deferred object’s resolution.

In my opinion, the asynchronous script calls are fairly easy to manage:

But what about a JSONP call? How do we squeeze that scenario into the jQuery.Deferred / jQuery.when() paradigm?

The approach I have taken starts with a variable that is set to an unresolved jQuery.Deferred object. As soon as you create this variable, you can then program around it. In the true spirit of JSONP, you can name your callback whatever you want. If the server supports JSONP, then you can assume that it will call your callback, passing in the much-desired return data.

Here is a pseudo-code walk-through:

Example # 1

In Example # 1, we have the core code that makes this all work. The interesting thing is that the actual JSONP call comes last. What we do beforehand is set up the tools we need to handle this asynchronous event. What makes this scenario a bit special is that you manually resolve the jQuery.Deferred object in the JSONP callback: “foo.resolve()”. This very nicely kicks in the .when() method that is chained to the return value of the jQuery.when() call.

Example # 2

In Example # 2, we have the code for the full working example. It builds upon the full working example from Part I of this article, but the added functionality has no connection to the form validation. The point that is (hopefully) being made here is:

  • This code provides a way to ensure that multiple asynchronously loaded dependencies are loaded before further action is taken.
  • This code checks to see if any of the asynchronously loaded dependencies have already been loaded in the page (possibly by hard-coded synchronous calls or another script).
  • This code allows for the inclusion of an asynchronously loaded JSONP dependency.

Going through the code line-by-line would be repetitive as that was already done in Part I. What might be helpful is to look at the code and see where the approach taken in Example # 1 has been worked into the full working code (Example # 2).

Here is the URL for the full working example: http://examples.kevinchisholm.com/jquery/deferred-and-when/complex-multi-async-dependencies.html

Summary

In this article we learned how to accommodate a JSONP call as an asynchronous dependency. We leveraged the jQuery.Deferred object and the jQuery.when() method to manage and act upon the resolution of the JSONP call.

Complex Multiple Script Loading Using the jQuery.when() Method and the jQuery.Deferred Object Part I

jQuery

jQuery LogoThe jQuery.when() method allows you to treat multiple asynchronous script calls as one logical event. But what if there is a chance that one or more dependencies are already loaded?

I just completed a project for a client that involved some tricky script loading logic. I had to use a jQuery plugin and icanhaz.js for templating (I prefer Mustache.js, but the previous developer had implemented icanhaz.js in many of the site’s templates). Now the difficult thing was that I had already written some JavaScript code that lazy-loads touts in the main navigation bar, which appears on every page in the site. So, the situation in hand was as follows:

  • My JavaScript depends on icanhaz.js and a jQuery plugin
  • icanhaz.js is asynchronously loaded further up the page
  • Since icanhaz.js is loaded asynchronously, I can’t assume it’s loaded when my new code runs
  • I don’t want to load icanhaz.js twice

eeesh….

I knew I could count on the jQuery.when() method to handle the multiple asynchronous script loads. Specifically, jQuery.when() can treat two or more asynchronous script load events as one event. The completion of the multiple events can represent one completed event, which can be used to tell the rest of your code: “hey, we have what we need, let’s proceed.” But at first I was not sure how to abstract the details of whether or not a script is already loaded. For example, If icanhaz.js has already been loaded in the page, I don’t want to waste time by loading it again (and potentially cause unexpected behavior because it loaded twice).

So I decided to leverage the jQuery.deferred constructor.

In short, for each script that needed to be loaded (i.e. each dependency), I wrote a function that checks to see if that script was already loaded. If so, then the function returns a resolved jQuery.deferred instance. If not, then I simply use the jQuery.when() method to wrap a jQuery.getScript() call, which returns an unresolved jQuery.deferred instance. So either way, my function returns a jQuery.deferred instance. This is perfect because jQuery can easily understand (and act upon) the “state” of a jQuery.deferred instance. And most importantly, jQuery can view multiple jQuery.deferred instances as one “event”.

“…..hmmmm Idunno Kevin, this is all starting to sound a little convoluted to me!”

I had similar feelings when I was working this out in my head. But once I fired up my JavaScript console, and started testing the code, it was not only easy to understand the logic, it worked flawlessly (serious kudos to the jQuery folks; these are awesome features).

So, for this article, I decided to use Mustache.js and the jQuery validation plugin as my dependencies. Mustache.js will be used to build the form and the jQuery validation plugin will provide form validation.

Example # 1

In Example # 1, we simply have the markup for the page. Not too much going on here: a page wrapper and two header elements. What it does illustrate is that the form and the validation you see when you run the final working example is all handled by our two dependencies: Mustache.js and the jQuery form validation plugin.

Example # 2

Now, in Example # 2, we have provided two constants which are simply the URLs for the script calls that we (might) have to make. This is a pattern that I like to follow, which can help to minimize clutter in your implementation code; make values that will never change constants and put them all in one coherent place.

The variable “data” simply holds an object literal that will be used by Mustache.js to populate the template, and the variable “template” is the string used by Mustache.js to create the template. (Notice the values inside of the double curly brackets: “{{}}”; these all map to properties in the “data” object.)

Example # 3

In Example # 3, we have a function that always returns a jQuery.deferred instance. The if/else statement provides two possible outcomes: Mustache.js is already loaded in the page or Mustache.js is not loaded. We test for the existence of window.Mustache (and the value of its “name” property) in order to determine the answer. If Mustache.js is already loaded, then we simply return a resolved jQuery.deferred object. If it is not, we then return a call to jQuery.when(), passing a jQuery.getScript() call as an argument. The jQuery.when method returns a jQuery.deferred instance that is in an “unresolved” state until the getScript() call completes.

The key point here is that even though in this case our function returns an un-resolved jQuery.deferred instance, the fact that it is a jQuery.deferred object is all we need.

So there is no need to walk through the function that does the same thing for the jQuery validation plugin; the logic is exactly the same. If you look at the code for the full working example at the end of this article, you’ll see that the only difference is the URL for the script that is loaded, and the way in which we determine if the plugin exists (i.e. we check for the existence of a property of the jQuery.prototype object named “formval”).

Example # 4

Now here in Example # 4, we create two variables. Both variables become a jQuery.deferred object because in each case, the variable is being set to the return value of the methods we just discussed in Example # 3: each of these methods returns a jQuery.deferred object. Again, these objects are in either a “pending” or “resolved” state, depending on whether or not the specified script was loaded.

Example # 5

{ //build the markup fom the template (uses Mustache.js) var form = Mustache.render(template,data); //inject the form $(‘#container’).append(form); //setup the form for validation (form validation plugin) $(‘#testform’).formval(); });

In Example # 5, look very closely at the first line: $.when(formValIsLoaded,mustacheIsLoaded). Essentially, this line says: “When the two arguments resolve…” that is, when both of these argument’s “state” changes to “resolved”. Now this is important because it’s treating the resolution of two or more events as one event. For example:

Event-A.completed + Event-B.completed = Event-C.done

So, this $.when() method will return when all of the arguments have a “resolved” state. Since the return value is also a jQuery.deferred object, then we can utilize its .done() method. We pass an anonymous function as an argument to the .when() method. This function will execute when all of the arguments of the .when() method are resolved.

Once we are inside of the anonymous function, we can be confident that our dependencies are loaded. At this point, there are just a couple of things left to do:

  • Create our form, using the Mustache.render() method, and inject it into the DOM
  • Set up validation using the jQuery.validation plugin

So, here we have it, the end result of all this work we have done, which is a simple one-field form. When you view the full working example (see link below), you can click the submit button to see the validation fail, which will cause the error message to show. And the label for the name field, the submit button’s text and the error message have all been supplied by the “data” variable in our code, which if you remember, is an object literal that contained all of those string values.

Example # 6

In Example # 6, we have the full code for our working example.

Here is the JsFiddle.net link for our full working example: http://jsfiddle.net/Ebj4v/5/

Final Proof of Concept

In the links that follow, we have added script tags to the code. In the first two cases, one of our dependencies is pre-loaded. In the third case both are pre-loaded. Chrome does not like the mimetype of the scripts as they are served from github.com, so please view these examples in FireFox. Open up your JavaScript console when viewing the examples. In each case, you will see a message indicating which dependency was pre-loaded. In all three cases, the resulting behaviour is the same: our code checks to see if a dependency is loaded, if so, great, and if not it loads it.

Mustache.js preloaded: http://jsfiddle.net/Ebj4v/6/

jQuery.validation plugin preloaded: http://jsfiddle.net/Ebj4v/7/

Both Mustache.js and jQuery.validation plugin preloaded: http://jsfiddle.net/Ebj4v/8/

Summary

In this article we learned how to solve a complex script-loading scenario. In doing so, we discussed the jQuery.deferred() constructor and jQuery.when() methods, learning how they can be leveraged to create an if/else logic so that we can determine whether or not a script was loaded, and then depending on the answer, take the appropriate action.

Helpful Links for jQuery.deferred and jQuery.when

jQuery.deferred

http://api.jquery.com/jQuery.Deferred/

http://api.jquery.com/category/deferred-object/

http://blog.kevinchisholm.com/javascript/jquery/using-the-jquery-promise-interface-to-avoid-the-ajax-pyramid-of-doom/

jQuery.when

http://api.jquery.com/jQuery.when/

Using jQuery Deferred to Manage Multiple AJAX calls

jQuery

jQuery LogoOnce you have become accustomed to making AJAX calls and consuming the contents of the data returned by the server, it is tempting to fall into a laid-back mind set: “hey, AJAX is AJAX right?… I mean… you open the request, you send the request, you wait for the server’s response, and then you do something with the response… no big deal, right?”

Well, yes, but… because of the asynchronous nature of an AJAX call, it does not take long for more complex scenarios to arise. What happens when you need to know about a group of AJAX calls? How can we treat a series of asynchronous events as a single value that we need to act upon once there is a collective “success” value?

Enter the jQuery.when() method. This handy dandy little tool allows you to treat multiple asynchronous events as a single value. The syntax is quite simple:

var B = $.get(serverPage.xyz); var C = $.get(serverPage.xyz); $.when(A,B,C).done(funtion(){ //act upon the collective success of A,B and C });

Some might find this a bit unusual. Normally, an AJAX call is something you simply “do,” not something you assign to a variable. jQuery allows us to treat an AJAX call as a value. This value translates to an object that has properties and methods. The $.when() method knows how to recognize and act upon these objects, so it presents a perfect way to handle multiple asynchronous events as a single value.

Example # 1

In Example # 1, we create the variable “aj1”, and set it to equal the result of an AJAX call. This variable becomes a jQuery “jqXHR” object. When we immediately inspect the object, we see that it has a number of methods. This is interesting, but not super interesting.

If you open your JavaScript console and then run this code, you will see the AJAX call in progress, and the contents of the jQuery “jqXHR” object. But if you wait a few seconds, and then after the AJAX call completes, you once again run the code: console.dir(aj1), you will see that this object has changed a bit. The “readyState” property is equal to 4, the “responseText” property contains some HTML from the server, the “status” property is equal to 200, and the statusText is: “OK”. Because the AJAX request has completed, this jqXHR object has properties that reflect this new state.

Example # 2

In Example # 2, we use the jQuery.when() method to act upon the completed state of the AJAX request. When using this syntax, the completed state of each request is a corresponding argument in the anonymous function that is passed to the .done() method. Now we have something interesting, because what we see is that each one of these success objects is an array. The first element is the response text of the request, the second element is the status of the request, and the third element is the original “jqXHR” object.

Example # 3

In Example # 3, we set up three AJAX calls. Normally, one might create a success handler for each AJAX call. In this case, we simply want to know when all three calls have completed successfully. We pass all three AJAX calls (i.e. the three variables that have been assigned the return value of each AJAX call), as arguments to the .when() method. Then we pass an anonymous function to the .done() method that is chained to the .when() method’s return value.

Just as with Example # 2, we take the success object for each call as the corresponding argument of the .done() method call. Inside of the .done() method’s callback, we take action; the contents of the $(‘#target’) element is removed, and we append the server response messages to that element.

Here is the full working example: http://examples.kevinchisholm.com/jquery/when/example-1/

Summary

If you have not had to wrestle with a scenario like this, you soon will. You’ll find that as web pages become more complex, AJAX is leveraged in more complex ways. When asynchronous activity is involved, any complexity is magnified. So, fortunately, the jQuery.when() method is an easy and effective way to handle multiple AJAX calls as one collective value.

Helpful Links for the jQuery.when() method

http://api.jquery.com/jQuery.when/

http://api.jquery.com/category/deferred-object/

http://stackoverflow.com/questions/5280699/jquery-when-understanding

 

Using the jQuery Promise Interface to Avoid the AJAX Pyramid of Doom

jQuery

jQuery LogoNested success callbacks are messy business. The jQuery Promise interface provides a simple and elegant solution.

So, you have to make an AJAX call, and then do something with the return data. No problem, right? Right. What if you have to make two AJAX calls, and then do something with the return data for each one? No problem, right? Right. What if the second AJAX call depends on the success of the first AJAX call?

“…um, well…. then, well… wait a minute… ok, I’ve got it:

I’ll make the first AJAX call…and then inside the success callback function, cache the data somewhere… um… in a global variable for now I guess… yeah, no one will notice. OK, and then inside of that success callback, we’ll nest another AJAX call, and then inside of the second AJAX calls’ success callback, we’ll get our first chunk of data from the global variable, and then, and then… um…and then…”

…yikes!

Obviously, the preceding diatribe was a little over the top, but c’mon…. haven’t you at least once stood at the edge of that cliff and looked over? Fortunately, jQuery features a way out of this mess that is safe, reliable and packed with vitamins.

The jqXHR object

Since version 1.5.1, jqXHR objects returned by $.ajax() implement a “Promise” interface. In short, this means that a number of methods that are exposed provide powerful abstraction for handling multiple asynchronous tasks.

I think it is important to note that the subject of the jQuery Deferred and Promise Objects is deep. It is not an easy topic to jump into and a detailed discussion of this is outside of the scope of this article. What I hope to accomplish here is to provide a simple and fast introduction to the topic, by using a real-world problem / solution.

There are certainly multiple scenarios in which the jQuery Deferred and Promise objects can be useful. I have chosen to use AJAX calls for this, since it is an example of asynchronous behavior that I think most folks can relate to. In order to dramatize the effect of an asynchronous AJAX call, I am using a PHP file that can return a delayed response. Here is the code for the server page:

OK, now some AJAX.

(Note: I highly recommend that you open up the “network”  panel in Firebug or WebKit developer tools so that you can see these AJAX calls in action when viewing the working examples… especially AJAX call # 1, which will take 5 seconds to complete)

Example # 1

In Example # 1 we have a fairly straightforward setup: Two buttons, each resulting in an AJAX call. Notice that the 1st AJAX call takes 5 seconds to complete. Instead of providing an inline anonymous function for the success callback of each AJAX call, we have a generic handler named “success”.

Here is a link to the working code for Example # 1: http://examples.kevinchisholm.com/jquery/promise/promise-and-ajax-beginner/example-1.html

But what if we want AJAX call # 2 to depend on AJAX call # 1? That is, we don’t want AJAX call # 2 to even be possible until AJAX call # 1 has completed successfully.

Example # 2

In Example # 2, we have a pattern that is known as the “Pyramid of Doom”. This might work for the short term, but it is impractical, not at all flexible, and just plain messy. What if there was a third button, and a fourth button… I think you see what I’m getting at here.

Example # 3

Ahhh… that’s much better!

In Example # 3, we have taken advantage of the Promise interface that is exposed as part of the jqXHR object. If you are wondering what the jqXHR object is, it is the return value of any $.ajax() call. So, while you can simply do this: $.ajax(URL,CALLBACK), the call itself returns a value. That return value is the jqXHR object, which is a superset of the XMLHTTPRequest object.

The return value of $.ajax() is the jqXHR object, which is a superset of the XMLHTTPRequest object, and packed with some powerful features.

We don’t have to dive too deeply into the good ol’ XMLHTTPRequest object (although it is important to know what it is and the critical role that it plays in AJAX). But the key point here is that the jqXHR object wraps the XMLHTTPRequest object, providing some useful features. One of those features is the “Promise” interface.

“….ok, ok Kevin, you’re givin’ me a migraine… where are you going with all this?”

Hang in there; we are at the 99 yard line here. What this all means is that instead of just making an AJAX call, you can assign that AJAX call to a variable. Since the $.ajax() method returns the jqXHR object, your variable is now a Swiss Army knife of AJAXian goodness. You can then implement methods of your object (i.e. your variable). Two of those methods are: .when() and .done();

So, in Example # 3, when we fired the first AJAX call, we assigned its return value to the variable “aj1”. Notice that we did NOT make a success handler call. We simply make the AJAX call, and that call’s return value is held by the variable “aj1”. Then when the user clicks the second button. we set the return value of the second AJAX call to the variable: “aj2”. Now we have two variables and each is a jqXHR object. These are powerful little objects!

The line where the fun really starts is: $.when(aj1,aj2).done()

Notice how the .done() function takes a callback. The callback is fired when the two arguments passed to the .when() method are resolved. And guess what those two arguments are… our two little jqXHR objects!

So, the .done() method knows how to get ahold of the data returned by each of those calls. Now we simply call our generic success handler, passing in the return data of each AJAX call (i.e. each jqXHR object). You may be wondering why I pass in the values “a[0]” and “b[0]”. This is because “a” and “b” are jqXHR objects. It just so happens that the first property of these objects (i.e. the property with the index of 0) happens to be the “responseText” property of that object (i.e. the text sent back from the server).

Phew!

I know that was a lot. But there is much to shout about when it comes to the jQuery Promise interface. As I mentioned, it is a big topic and not easily summarized. But my hope is that these examples will have put a little context around the subject, and will help you to dive in and get started.

Below is the source code for this article’s full working example:

Example # 4:

Here is a link to this article’s full working example: http://examples.kevinchisholm.com/jquery/promise/promise-and-ajax-beginner/example-2.html

Summary

In this article we learned about the jQuery Promise interface. We discovered that since version 1.5.1, calls to $.ajax() return a jqXHR object, which implements the Promise interface. We utilized the .when() and .done() methods of this interface to execute callback functions for two asynchronous tasks. This eliminates the need for nested success callback functions.

Helpful Links for the jQuery Deferred, jQuery Promise and jqXHR Objects

jQuery Deferred

http://api.jquery.com/category/deferred-object/

http://api.jquery.com/jQuery.Deferred/

jQuery Promise

http://api.jquery.com/promise/

http://api.jquery.com/deferred.promise/

http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/

jQuery jqXHR

http://api.jquery.com/Types/#jqXHR

http://api.jquery.com/jQuery.ajax/#jqXHR

What’s the Difference Between jQuery().each() and jQuery.each() ?

jQuery

jQuery LogojQuery’s two .each() methods are similar in nature, but differ in level of functionality

Some may find it difficult to understand the difference between jQuery.each() and jQuery().each(). Perhaps the easiest way to understand the difference is to start with jQuery().each(). This method can only be used against a jQuery collection. So when you do this: jQuery(‘#someDiv p’).each(), what you are saying is: “for EACH paragraph that is inside of the element with the ID of “someDiv”, I want to do something. That’s it.

The jQuery.each() method is a static method of the jQuery object. This means that it is just a method that’s out there for you to use, and you need to give it a little more info. But there is a bigger payoff with this method: it can be used to iterate over different kinds of things, not just a jQuery collection.

The syntax for the jQuery.each() method is also simple:

So, OBJECT can be an object, an array, an array-like object or even a jQuery collection. How cool is that? The CALLBACK is a function that will be run against each element in the first argument. The super-star feature here is that the first argument can be a jQuery DOM collection. This means that jQuery.each() can do ANYTHING that jQuery().each() can do. Let’s jump into some code:

jQuery().each()

Example # 1.A

In Example # 1.A, we have an unordered list, with the days of the week as list items. The last two have the “weekend” class applied. We use the $().each() method twice. In the first run, it will iterate over every one of the list items. In the second run, the jQuery collection contains only the last two list items because they have the “weekend” class.

In both cases though, we can see how the $().each() method does one thing and does it well: it iterates over a jQuery collection. Inside of that collection, we use $(this) to get a reference to the current element being iterated over.

Here is the JSFiddle Link for Example # 1.A: http://jsfiddle.net/wcRmd/

 

Example # 1.B

In Example # 1.B, we take advantage of two additional features that the jQuery().each method has to offer. The callback takes two optional arguments: the index of the current element being iterated over, and the element itself. In our example, we add the index of each element to its text, and we do so by referencing ‘element’ instead of ‘this’. Keep in mind that ‘element’ is just what we decided to name that argument variable. We could just have easily named it ‘foo’ or ‘glove’. It doesn’t matter what you name these variables, just as long as you are aware of what they are.

We also used the .hasClass() method to see if each element had the “skip” class. This was just a way to illustrate the fact that while you CAN do things to each element inside of the callback function, you can also choose not to. There are numerous ways that you can organize this kind of logic. Using the ‘skip’ class was merely a ‘quick and dirty’ approach.

Here is the JSFiddle Link for Example # 1.B: http://jsfiddle.net/9C8He/

jQuery.each()

Example # 2.A

In Example # 2A, we pass-in two arguments to the static jQuery.each() method: an array and an anonymous callback function. The array has three elements, and the callback merely outputs the value of each array element to the console. Pretty simple stuff.

Here is the JSFiddle Link for Example # 2.A: http://jsbin.com/epanov/1/edit

 

Example # 2.B

In Example # 2.B, we provide an object as the first argument to the jQuery.each() method. When iterating over an object, the jQuery.each() method will return the property name for ‘index’. This is a brilliant approach, as it provides a very flexible alternative to the native JavaScript “for/in” loop.

Here is the JSFiddle Link for Example # 2.B: http://jsbin.com/examuz/1/edit

 

Example # 2.C

In Example # 2.C, we provide a jQuery DOM collection as the first argument to the jQuery.each() method. Essentially, this is just like using the jQuery().each() method. Inside of the callback function, ‘index’ can be used to get a numerical reference to the current element being iterated over, and ‘value’ will be the element itself. Brilliant.

NOTE: You may wonder why the last two elements have indexes of 0 and 1 respectively. This is because we specified that list items with the ‘weekend’ class should be returned in the collection. So, our jQuery collection object contains only two elements (‘saturday’ and ‘sunday’).

Here is the JSFiddle Link for Example # 2.C: http://jsfiddle.net/XjxvZ/

 

Summary

In this article we learned the difference between the jQuery.each() and jQuery().each() methods. We also discovered that while they do differ, the jQuery.each() is flexible enough to provide the same functionality as jQuery().each() if needed.

Helpful Links for jQuery().each() and jQuery.each()

jQuery().each()

http://api.jquery.com/each/

jQuery.each()

http://api.jquery.com/jQuery.each/

Super Flexible JavaScript Object and Array Iteration with jQuery.each()

jQuery

jQuery LogoThe jQuery.each() method makes it trivial to iterate over or inspect any kind of collection: arrays, objects, array-like objects, even jQuery DOM Objects.

Working with JavaScript means working with Objects. There is almost no way around this. So even in the simplest of scenarios, at some point you are likely to encounter an object and you need to inspect it.

Keep in mind that in JavaScript, there are different kinds of objects. For example, an array is an object. And, a DOM element is an object. It’s no secret that I am a huge fan of the JavaScript “For/In” loop. If you are not able to use jQuery then that is your go-to tool for object inspection. If you are using jQuery, then the static .each() method is a real winner.

It is important to make sure you understand that this is not the same thing as the $().each() method. When you pass a CSS selector to jQuery and then call the .each() method on the collection that is returned, you are calling a different method in jQuery. It is very similar, but that syntax is meant especially for DOM collections.

The jQuery.each() method is a static method of the jQuery object. It is a more generalized method that can be used to iterate over any object, array or array-like object. So the syntax is quite simple:

The OBJECT argument is any object, array or array-like object. The CALLBACK argument can be an inline anonymous function, a named function expression or a variable that points to an anonymous function.

Example # 1

 

In Example # 1, we have provided a simple array: three strings, each representing a corresponding day of the work week. The callback function executes for each one of the array elements, and inside of that function the variable “value” represents the value of that array element. We could have called that variable “baseball”; it doesn’t matter what you call it. The most important thing to remember is that the second argument to the callback will return the value of the current array element that is being iterated over. So, simple stuff.

Here is a JSBin link for Example # 1: http://jsbin.com/epanov/1/edit

 

Example # 2

In Example # 2, we take advantage of the “index” argument. In the console, we output the value of that variable. Again, this variable can be named anything. As with “value”, it’s most important to be aware that the first argument of the callback will return the index of the array element that is currently being iterated over.

Here is a JSBin link for Example # 2: http://jsbin.com/epezuc/1/edit

 

Example # 3

In Example # 3, we take things a step further to illustrate the fact that we can not only access the value of the current array element, but we can do things with it. Here, we simply remove ‘day’ from the string. But there is certainly a whole lot more that one might do. For example, if these array elements were objects instead of primitive strings, we could make changes to the objects and the next person or function who reached for that object would find it changed.

Here is a JSBin link for Example # 3: http://jsbin.com/okoxej/1/edit

 

Example # 4

In Example # 4, we move the object out of the jQuery.each() call and then simply reference it as the variable “data”. This time we have provided an array of objects. So on each iteration of the callback, instead of simply outputting a string, we are inspecting an object.

Here is a JSBin link for Example # 4: http://jsbin.com/usewoj/1/edit

 

Example # 5

In Example # 5, things get even more interesting. Here, we can see the brilliance of the jQuery.each() method. In this case we provide an object literal as the first argument to the .each() method. When an object is passed in, then the value of the “index” variable will be the name of the key or property of the object. So this saves you the time it would take to roll your own “For/In” loop.

Here is a JSBin link for Example # 5: http://jsbin.com/examuz/1/edit

 

Example # 6

In Example # 6, the object that is provided is a jQuery collection object. So now, on each execution of the callback, we can use $(this) to reference the jQuery DOM element object that is being iterated over, and of course do all the usual kinds of fun things to the element with jQuery.

Here is a JSFiddle link for Example # 6: http://jsfiddle.net/n7PRD/

 

Example # 7

And here, in Example # 7, we have abstracted the callback. Instead of providing an inline anonymous function, we provide a reference to a variable that is a function: “inspect”. So, that function will be called for every element provided in the data. The data we have provided in an array, and each element of that array is an object with some user account data. Phew! So, on each iteration of the callback (which is really the variable “inspect”, which is a function), we output the contents of that object to the console. We certainly could have done much more here, but the point of the example is that you can abstract any aspect of this that you like. So, as you can see, there is a ton of flexibility here and you are only limited by your imagination.

Here is a JSBin link for Example # 7: http://jsbin.com/iriwer/1/edit

 

Summary

In this article we learned a bit about the jQuery.each() method. We discussed the simple syntax, as well as the two arguments that are used in the callback. We also explored multiple scenarios such as inspecting an array of strings, inspecting an array of objects, inspecting objects and inspecting jQuery DOM objects.

Helpful Links for the jQuery.each() Method.

http://api.jquery.com/jQuery.each/

http://www.jquery4u.com/jquery-functions/jquery-each-examples/

http://stackoverflow.com/questions/722815/jquery-each-practical-uses

jQuery Plugin Authoring – The Absolute Basics – Part II

jQuery

jQuery LogoOnce you have jQuery plugin basics down, it’s time to implement some best practices

In the previous post “jQuery Plugin Authoring – The Absolute Basics – Part I”, we to a detailed look at the architecture of a jQuery plugin. Now that you understand the building blocks, let’s discuss a few best practices. These techniques are considered standard for quality jQuery plugin authoring, and will dress you for success.

Protecting the Dollar Sign

Most jQuery consumers associate the dollar sign with jQuery. But that dollar sign is simply a shortcut to the jQuery object, which is a property of the window object. You could write all of your jQuery code without ever using the dollar sign, and simply “jQuery” instead. But most people prefer the dollar sign because it is of course quite a bit easier and faster to type.

But jQuery offers a “no conflict” mode that allows another library to take over the dollar sign. It is considered best practice to anticipate this scenario and pass the global jQuery object into the immediate function that wraps your plugin. This way, inside of the nice and safe sandbox of your plugin, you can use the dollar sign all you like, without the slightest concern for how it is being used in the global context.

Example # 1

In Example # 1, we pass the global jQuery object into the immediate function. The immediate function takes that jQuery object as “$”, so from there on we are free to use the dollar sign safely, even if jQuery is in no-conflict mode.

Chainability

Method chaining is a popular technique in JavaScript. Many web developers use this technique when they leverage jQuery without even knowing it. How many time have you seen something like this:

$(SOME PARENT).find(SOME CHILD).CSS(“prop”,”val”).click();

What signifies the chaining activity is the fact that we have only one reference to the jQuery collection returned by $(SOME PARENT). Since each method used returns the jQuery object, we can use that return value to invoke another jQuery method, and so on. This is called “Chaining” method calls together.

It is considered best practice to allow method chaining when authoring your own jQuery plugin. Doing so is quite simple; you just need to return the jQuery object from each method.

Example # 2

In Example # 2, we return “this” from our plugin function. It’s important to note where the return statement is. Because the return statement occurs as the last line of code in our plugin’s function, the jQuery collection object is returned to the next method that wants to “chain”, without the need to re-state a jQuery collection.

Example # 3

In Example # 3, we have an example of method chaining in jQuery. Note that $(‘a’) only occurs once. That call to jQuery returns a jQuery collection object, which is returned from our jQuery plugin. As a result, the .attr() method can “chain” onto that return value and function properly.

Example # 4

In Example # 4, we have an even more complex example of method chaining. First we invoke “myPlugin”, and the the jQuery methods: .attr(), .css() and .click()

Here is a fully working JSFiddle.net link that demonstrates the best practices we have covered in this article. Be sure to click a few of the links to demonstrate the method chaining from example # 4:

http://jsfiddle.net/fTA95/

Summary

In this article we discussed a few jQuery plugin authoring best practices. We covered how to safely use the dollar sign in your plugin code, even when jQuery is in no-conflict mode. We also covered how to implement method chaining.

Helpful Links for jQuery plugin authoring

http://docs.jquery.com/Plugins/Authoring
http://stackoverflow.com/questions/12632382/jquery-plugin-authoring-and-namespacing

jQuery Plugin Authoring – The Absolute Basics – Part I

jQuery

jQuery Logo

You know a little jQuery, you have used a few jQuery plugins, and now you want to write your own jQuery plugin. Don’t worry, it’s no big deal. In fact it’s fun.

If you have been putting off authoring your first jQuery plugin, it’s time to wrap a bandana around your head, fire up “The Eye of the Tiger” by “Survivor” and figure out how to defeat Apollo Creed. Sorry, for the cheesy 80s reference, I couldn’t resist.

But seriously, it really is no big deal. The most important thing is to get a firm grip on the fundamentals. That part is serious. If you don’t understand what you are doing from a jQuery-architecture standpoint, then you will quickly find yourself in a quagmire of muck and filth, and you don’t want that.

In this article we will discuss the absolute basics of how to author a jQuery plugin:

  • Wrapping your plugin in a self-executing anonymous function
  • Extending the jQuery prototype,
  • Iterating over each element in the jQuery collection returned by your plugin.

This is the big stuff. Once you get your noggin around these concepts, the fun can begin.

A note about Self-executing anonymous functions

These are otherwise known as “immediate functions”. An immediate function is simply a function that is wrapped in parentheses, and followed by a pair of parentheses:

You can learn more about immediate functions in my blog post:Immediate Functions in JavaScript – The Basicsas well as my blog post:Using an Immediate Function to Create a Global JavaScript Variable That Has Private Scope

The main point here is to make sure you are comfortable with the concept of an immediate function in JavaScript. It’s important to do before reading further.

Where does my jQuery plugin code go?

Good question. The answer is: In its own file. By convention, you’ll want to create a JavaSript file named jquery.myPlugin.js. Then you’ll need to reference it just as you would any other JavaScript file:

Just make sure you reference jQuery before you reference your plugin.

For simplicity sake, we will reference our jQuery plugin via a set of SCRIPT tags, right in the page (that is perfectly valid, but definitely not practical).

Example # 1

In example # 1 we have the absolute bare-bones code needed for a jQuery plugin. Here are the important points to consider for example # 1:

Wrap your jQuery plugin in an immediate Function

This is considered a best-practice and for good reason. Taking this approach allows you to create as many variables as you need in your plugin, without polluting the global namespace. Don’t overlook this, it allows you complete freedom with regards to the number of variables you need to create, and sandboxes all of these variables very nicely.

Again, an immediate function is simply a function that is wrapped in parentheses, and followed by a pair of parentheses. It fires right away when the JavaScript is evaluated, you don’t need to (and cannot) call the function. It just fires right away and whatever code you implement in that function executes. It’s a great way to provide private variable scope to some code without a whole lotta fuss.

If you are still having a tough time with the concept of immediate functions, stop, do a google search for JavaScript Immediate Function, learn it, live it, ask it out on a date, marry it, and then come back here to keep on reading.

https://www.google.com/search?q=javascript+immediate+function

(I’m serious about this immediate function thingy)

Your jQuery plugin becomes a property of the jQuery prototype object

jQuery is a function. Actually, the code in jQuery follows the factory pattern and returns a function that in-turn returns different kinds of things, depending on what you pass into that function. Most of the time, it returns an HTML collection wrapped with jQuery (hence a jQuery collection object), but again, the actual return value depends on what you are passing in.

Every JavaScript object has a prototype property, this includes functions. jQuery exposes its prototype property as “fn”. So, you simply assign your plugin to be a property of that “fn” object. Once you have done that, jQuery now has a new method that is YOUR plugin.

Now you can do this:

Inside of your plugin, the JavaScript keyword “this” is already a jQuery object

Most people know that inside of a jQuery callback, “this” usually refers to the current native DOM element that is being iterated over. When you wrap “this” in jQuery, it becomes a jQuery object. So, we often refer to “this” as “$(this)”.

Inside of your plugin, there is no need to do that because the JavaScript keyword “this” is already a jQuery object. If you refer to “this” as “$(this)”, it’s not going to kill anyone, but it is not necessary and just uses more memory than is needed.

Your jQuery plugin returns a jQuery collection

What your jQuery plugin returns depends on the CSS selector that was passed-in. For example, if you do this: $(body).myPlugin(), your jquery plugin will return a jQuery collection that has exactly one element: the BODY tag of your document (unless of course you have more than one BODY element in your page, which would be a bit of a head-scratcher). So, if you have an unordered list that has for example three items, and you invoke your plugin like this: $(ul li).myPlugin(), then your plugin will return a jQuery collection that contains three elements.

Use this.each() to iterate over all of the elements that are returned by your jQuery plugin

jQuery’s .each() method is a lovely little tool that allows you to iterate over a jQuery collection and “do something” to each element. Keep in mind that a jQuery collection can always contain exactly one element, and when it does, then the .each() method will run once. But when a jQuery collection contains multiple elements, then the .each() method will run once for EACH element in that collection.

When you use the .each() method, you pass in an anonymous function, and inside that function you have access to the current element that is being iterated over. It is here that you will need to wrap “this” with jQuery if you want it to be a jQuery object: Use $(this) for the jQuery object that represents the current element, or simply “this” for the native DOM element implementation. This anonymous function takes as its first argument the index of the current element. This is surprisingly handy: what if you want to know if this the the first element in the collection? or the last? That index number will help you with that task.

Now you are ready to write some awesome jQuery plugin code

Thanks for hanging in there. The preceding details were important. I know you are anxious to write some code, but understanding the outer architecture of a jQuery plugin is critical. If you do not understand what was just covered, then you will quickly be awash in spaghetti code that is not working right and will be difficult to debug. I promise you.

Example # 2

In example # 2, we invoke our jQuery plugin. We wrap it in a $(document).ready() call so that it only fires once the document is ready.

Invoking our plugin is as simple as $(CSS SELECTOR).myPlugin().

This is because our plugin is a property of the jQuery prototype object, which makes it a completely valid jQuery method. Nice.

Example # 3

In example # 3, we see how our plugin can behave differently depending on what we pass into it. In each case, the jQuery collection object returned by our plugin will differ, depending again on what CSS selector we passed-in.

Example # 4

In example # 4, we have included some implementation code so that our jQuery plugin actually does something. I this case, for each element returned in the jQuery collection, we change the CSS so that the element’s color is green, the background color is yellow, and the font is “Comic Sans”. Not too pretty, but just enough so that when we run the code, we can see that our plugin is working perfectly. More importantly, if you vary the CSS selector that is passed-in, you will see that our plugin behaves differently in each case (i.e. the HTML elements that become green with yellow backgrounds and Comic Sans font will vary).

Full Working Code for this Article
http://jsfiddle.net/wdUtL/

Full Working Code for this ArticleWith Comments
http://jsfiddle.net/ewTez/

Summary

In this article we discussed the absolute basics of how to author a jQuery plugin. We covered how to wrap your plugin in a self-executing anonymous function, how to extend the jQuery prototype, and how to iterate over each element in the jQuery collection returned by your plugin.

This example provided in this article was very simple. The main purpose of the article was to provide the overview needed so that you understand how a jQuery plugin is constructed, how it works at the most basic level, and importantly how the value of the JavaScript keyword “this” will vary a bit, depending on where you are in the code.

With a firm understanding of how a jQuery plugin is constructed, we can move on to best practices and more intermediate jQuery plugin authoring techniques.

Helpful Links for jQuery plugin authoring basics

http://docs.jquery.com/Plugins/Authoring

http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/

http://blog.kevinchisholm.com/jquery/jquery-each-method/

 

Harnessing the Power and Simplicity of jQuery.append() and jQuery.prepend()

jQuery

JavaScript LogoI’m a big believer in making sure that you understand what is going on under the hood when you use jQuery. But there are times when it just makes sense to leverage jQuery; otherwise you would literally wind up just writing your own library.

One of the many such cases is when it comes to creating elements and then injecting them into the DOM. So let’s jump right into a few examples which will make it easier to highlight these features.

First, here is the markup we will be working with for all of the examples:

 

Native JavaScript

Example # 1:

Here is the JsFiddle link for Example # 1: http://jsfiddle.net/pvwP4/

When it comes to injecting new elements into the DOM, these methods virtually eliminate the verbose syntax of Native JavaScript

In Example # 1, I wanted to quickly review the absolute minimum native JavaScript needed to append text to an element in the page. Needless to say, if you want to accomplish anything useful, such as appending an unordered list, or complex markup that involves nested elements or images, etc., then you will wind up writing a bit of code. That’s just the state of native JavaScript today.

I tend to use jQuery as little as possible, mainly as an exercise in keeping my native JS skills sharp. But when it comes to creating and appending elements, jQuery.append() and jQuery.prepend() are hard to beat. It just saves so much time.

jQuery.append()

Example # 2: 

Here is the JsFiddle link for Example # 2: http://jsfiddle.net/tWSW8/

So, in Example # 2, our three lines of JavaScript have been reduced to one line of jQuery. Nice.

Example # 3:

Here is the JsFiddle link for Example # 3: http://jsfiddle.net/9pHQ2/

And here in Example # 3, we get into the fun stuff. First, one of the absolute joys of jQuery: the ability to create a DOM element by simply passing a set of opening and closing HTML tags to the $() method. Here I pass in an opening and closing DIV tag, and that’s it; we now have a reference to a new element that, while not yet in the DOM, is in memory and fully available to us for whatever we need. We then use a for loop to create LI elements using string concatenation.

Example # 4:

Here is the JsFiddle link for Example # 4: http://jsfiddle.net/mExAw/ In Example # 4, we start to put jQuery.append() to work. So inside of a for loop, we dynamically create list items, and append them to an unordered list. In order to keep things simple, we just use the value of the counter as the text. A more real-world example would be consuming JSON, and for each item in that JSON, creating the markup we need for the page.

Example # 5:

Here is the JsFiddle link for Example # 5: http://jsfiddle.net/JMy2J/

So now, in Example # 5, we turn things around by using the jQuery.appendTo() method. It could not possibly be simpler. Instead of UL.append(LI), we just say: LI.appendTo(UL). In other words, first we said: “…to that UL, append this LI”, and now we are saying: “…append this LI to that UL”.

jQuery.prepend()

Example # 6:

Here is the JsFiddle link for Example # 6: http://jsfiddle.net/D3B7G/

In Example # 6, we demonstrate the jQuery.prepend() method. There certainly is no mystery to this: it provides the opposite functionality of jQuery.append(). We create an unordered list, just as we did in the previous examples, but then we create another set of LI elements, and prepend them to the UL. I specifically counted down from 10, so that it would be obvious in the example that we have used jQuery’s prepend() method, and not append().

Example # 7:

Here is the JsFiddle link for Example # 7: http://jsfiddle.net/HqKv7/

Example # 7 is virtually the same as Example # 6, except we use jQuery.prependTo(), instead of jQuery.prepend().

Summary

Although this post is focused on jQuery.append() and jQuery.prepend(), we’ve also seen how easy it is to create elements with the $() function. While it is always good to make sure you understand what jQuery is doing and that you can write native JavaScript to accomplish your tasks, jQuery just makes perfect sense in many situations. As you can see, the main reason is that it abstracts away a lot of the time-intensive tedium of cross-browser compatibility.

Helpful Links for jQuery.append() and jQuery.prepend()

jQuery.append()

http://api.jquery.com/append/

http://www.w3schools.com/jquery/html_append.asp

jQuery.prepend()

http://api.jquery.com/prepend/

http://www.w3schools.com/jquery/html_prepend.asp

JavaScript animation with jQuery.animate() – Introduction

jQuery

jQuery Logo
“How can I animate web page elements with JavaScript, using jQuery”?

Animation in JavaScript can be tricky. What at first may seem easy, quickly becomes a scattered mess of timeouts and callbacks. But with jQuery.animate(), you have a simple and elegant way of implementing animation in your web page, without all the headaches and jerky performance.

jQuery.animate() has a very simple syntax: Chain the return value of a jQuery collection with the .animate() method, pass in an options object, a speed value, and off you go. It really is that simple.

Before we get into the examples, here is the markup we will use:

Example # 1

Here is the jsFiddle.net Link for Example # 1: http://jsfiddle.net/jPaHy/

In Example # 1, we use a jQuery selector to return a collection. In this case, the collection contains only one element. Here’s a rundown of the syntax:

  • The jQuery selector “$(“.moveMe”)” returns a collection of one element
  • We chain-in the .animate() method to that return value
  • We pass-in an object to the .animate() method as the first argument
  • In that object, we have one property: “left”, and the value is: “+=500px”
  • The second argument that we pass in is the speed, which in this case is 4000 miliseconds (i.e. 4 seconds)

And that’s it!

Example # 2

Here is the jsFiddle.net Link for Example # 2: http://jsfiddle.net/BRWDr/

In Example # 2, we add a second chained .animate() method. There is little difference in the second call; instead of manipulating the “left” property, we manipulate the “top” property, which pushes the text down by 200 pixels.

Example # 3 – Using the jQuery.animate() callback function

Here is the jsFiddle.net link for Example # 3: http://jsfiddle.net/8FZ87/

In Example # 3, we pass-in a third argument. This, of course, is the callback function. What this means is that when jQuery.animate() finishes with the animation, it runs the callback function, if one is passed-in. You could certainly pass-in a named function, or as we have done, you can pass-in an anonymous function. In the callback, we change the color of the text to red, and change the text in the element to “all done!”.

Summary

The amount of JavaScript we would have had to write to accomplish this would have been a total pain in the neck. All that code is in jQuery, and it abstracts away the details, leaving you with a syntax that is both simple and elegant.

Once you have mastered the simple syntax of jQuery.animate(), moving elements around the page becomes trivial

Notice that in the markup, I applied the following CSS to the element that we want to animate: “position: relative;” We needed this because our examples manipulated the “left” and “top” properties. So, if the element was not positioned, nothing would happen when the JavaScript code ran.

The jQuery.animate() method makes it trivial to animate elements in a web page. Once you learn the syntax, it is incredibly easy. Of course, there is much more that can be done, and some impressive advanced features are available. This tutorial was meant only to explain the absolute basics of jQuery.animate(), so that if you have never used it before, you can get started right away.

Helpful Links for the jQuery.animate() method

http://api.jquery.com/animate/

http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_animation

http://viralpatel.net/blogs/understanding-jquery-animate-function/

http://james.padolsey.com/javascript/fun-with-jquerys-animate/

http://james.padolsey.com/demos/jquery/easing/

What’s the difference between jQuery.ajax(), jQuery.get() and jQuery.post()?

jQuery

jQuery LogojQuery offers three Ajax calls that are simple and painless

Although it is a good idea to understand Ajax in the context of native JavaScript, leveraging the power of JavaScript libraries for your Ajax calls is not a bad idea. Depending on the size and complexity of your application, it can often minimize the amount of code you need to write in order to provide the best cross-browser experience.

Question: “What is the difference between jQuery.ajax(), jQuery.get() and jQuery.post() ?”

Answer: jQuery.get() and jQuery.post() contain features that are subsets of jQuery.ajax().

So jQuery.ajax() is the method that provides the most flexibility of the three. You’ll see that the biggest difference from an implementation standpoint is that you pass an object to jQuery.ajax(), which contains the necessary parameters. And as for jQuery.get() and jQuery.post(), here you pass in arguments. So you might say that jQuery.get() and jQuery.post() are both shorthand for jQuery.ajax().

Important Note: Because of the “Same origin policy” enforced by all browsers, I could not make a jsfiddle example for this post. But you can copy and paste these code examples into a simple html file, and just make sure that is a file named test.txt in the same folder. Put a simple message in that text file (i.e. “hello from the text file”).

jQuery.ajax()

Example # 1

So, in Example # 1, we use the jQuery.ajax() method. There are certainly more configurable parameters, but here we are using the bare minimum.

You’ll see that there is not much going on here. We just pass an object into the jQuery.ajax() method. That object has four properties: “url,” “dataType,” “type,”  and “success”, and here are the details for each property:

  • url: This is the URL of the file that you want to grab via your ajax call.
  • dataType: This determines how the return data will be treated (i.e. pure text, html, XML, etc.).
  • type: This the the request type. Choose “GET” or “POST”. This is actually optional; if you omit it, jQuery will default to “GET”.
  • success: This is a callback function that is fired after a successful http request has completed. The first argument to the function is the data returned from the server. There are other arguments that can be passed in as well.

As long as you have a file named “test.txt” that has some kind of message, and it is in the same folder as your html file, the contents of that text file will appear in your JavaScript console. (Don’t forget to open the console! : – ). Of course, you can put that file anywhere you want, as long as it is on the same domain as the requesting file.

A video tutorial, explaining the difference between jQuery.ajax(), jQuery.get() and jQuery.post()

Here, in this video, I briefly explain the difference between these three AJAX utilities. You’ll see that I demonstrate how jQuery.get() and jQuery.post() are very similar, and how jQuery.AJAX is a more generalized method that allows you to make either GET or POST AJAX requests.

jQuery.get()

Example # 2

Now here, in Example # 2, we use the .get() method, which is a kind of shorthand for jQuery.ajax(). When using jQuery.get(), instead of passing in an object, you pass in arguments. At minium, you’ll need the first two arguments: the URL of the file you want to retrieve (i.e. ‘test.txt’), and a success callback. In this example, we also passed in a third argument: ‘text,’ which told jQuery that we wanted to treat the return message as text.

The jQuery.get() method is recommended when you want to make a quick and dirty Ajax call and you are sure it will be a GET. So here, there’s not much more to it. Short and sweet.

jQuery.post()

Example # 3

And finally, in Example # 3, we used jQuery.post(). And in exactly the same manner as jQuery.get(), this method is like using jQuery.ajax(), and specifying a “type” of “POST.” So, this method is recommended if you need to make a quick Ajax call via POST, and don’t need to make a lot of configuration decisions.

What About Multiple AJAX Calls?

When you have code that depends on the mutual success of multiple Ajax calls, things can get messy. Quite often, a developer might implement an AJAX call inside the success function of another one. This can work, but what if there is a total of three AJAX calls? or even four? Well, what you wind up with is a pattern called the “Pyramid of Doom”:

The Pyramid of Doom is a JavaScript anti-pattern that should be avoided. If you are already using jQuery, you can leverage the power of the jQuery.when() method, which can be leveraged to treat multiple AJAX calls as one asyncronous event:

To learn more  about using the jQuery.when() method to manage multiple AJAX calls in JavaScript, you can read these posts:

http://blog.kevinchisholm.com/javascript/jquery/using-jquery-deferred-to-manage-multiple-ajax-calls/

http://blog.kevinchisholm.com/javascript/jquery/using-the-jquery-promise-interface-to-avoid-the-ajax-pyramid-of-doom/

Summary

If you are wondering whether you should use jQuery.ajax(), jQuery.get() or jQuery.post(), it is really up to you. One way to approach it might be to ask yourself: “Am I writing a multi-purpose function that will be able to perform either a GET or a POST? And I do I want this function to accommodate dynamic settings such as dataType or data?” If the answer to these questions is “yes,” then use jQuery.ajax(), and wrap it with your own custom function that takes an object as an argument. If you are thinking “nah, I just need to make a quick GET or POST Ajax call, then get the data, do something with it, and use jQuiery.get() or jQuery.post().

Helpful Links for jQuery.ajax(), jQuery.get() and jQuery.post()

http://api.jquery.com/jQuery.ajax/

http://www.w3schools.com/jquery/jquery_ref_ajax.asp

http://api.jquery.com/jQuery.get/

http://api.jquery.com/jQuery.post/

Iterating Over a DOM Collection with the jQuery.each Method

jQuery

jQuery Logo - each method
jQuery makes it super easy to get a reference to a collection of DOM elements. The jquery.each method allows you to execute a function against each one of the elements in the collection.

Solving problems is one of jQuery’s best qualities, and the beauty of the jQuery.each method is that it solves a very common problem: how to iterate a collection of DOM elements. Now in order to work through this task, one might be inclined to set up a for-loop. This approach is not at all wrong; in fact, on some levels it makes perfect sense. The thing is, in tackling it this way you run into a few avoidable problems. First, there is a lot of boilerplate code. In other words, to set up the for-loop you would need a counter variable, which we’ll call “i”. And since we might want to iterate a collection of DOM elements more than once, we’d need to make the “i” variable private, which means using a function to create private or “local” scope. Also, 80% of our for-loop would be repeated code. So, you get the picture… our problems are mounting, and they most assuredly are avoidable. So, here’s where the beauty of the jQuery.each method comes into play: it provides abstraction for creating a for-loop. This means that we need only provide the collection and a callback method that we wanted executed for each iteration of the loop.

The jQuery.each method is the go-to tool when you need to iterate a collection of DOM elements. Let’s say you have a bunch of elements in the page. Maybe that bunch is “every <a> tag” or “every <li> inside of the <ul> with the class sales”, or each <div> element that is a child of <div class=”members”>.

Here is how you would create a reference to each of those collections

jQuery will return a collection with one or more members. But how do you iterate over that collection and “do something” to each one? You can accomplish this by chaining the .each() method to the return value, and of course, pass a callback to that method.

jQuery.each Method – Basic Syntax

In the above example, where you see “selector”, that represents a CSS-like query such as “p” or “#some-id p img”, etc., that you would pass to jQuery. Now you can see that we have passed a callback function to the each() method. And inside of that callback, we would take care of any tasks that are specific to the elements over which we are currently iterating.

So, for an example, we will create a click-event handler for each <li> inside of a <ul>. Here is the markup we will work with:

With that markup in mind, consider the following code:

Example # 1

Notice that in Example # 1 we use $(this). Now just in case you are not familiar with this pattern, $(this) equals “the current element”, and it happens twice in our code. The first instance of $(this) on line # 2 refers to the element that is currently being iterated over (i.e. the current “UL LI”). The second $(this) on line # 3 represents the element that was just clicked. This is because we want to change the color of the element that was just clicked to red.

From a pseudocode perspective, here is what we have done:1- For each <li> that is inside of a <ul>, add a click event handler
2 – In the click-event handler, we say “If you click me, make my text red”

Example # 2

In Example # 2, we change the logic a bit so that only an <li> with the class “workday” is returned in the collection, which means that the “saturday” and “sunday” <li> elements do have a click event handler assigned.

Here is the JsFiddle link for this example: http://jsfiddle.net/WHkkA/. Simply remove the .workday class from the CSS selector to see Example # 1 work.

Summary

The jQuery .each() method is used to iterate over the members of a jQuery collection. There is definitely more fun stuff that can be done with this method, but this is just a very basic overview of what the method does and how to use it.

Important Note: Try not to confuse this with the jQuery.each() method. That is a similar concept, but more of a general-purpose iteration method that is a static method call to the jQuery object, not a method of a jQuery collection.

How to Use the jQuery replaceWith Method

jQuery

JavaScript LogoThe replaceWith() method provides a way to completely remove an element and put another in its place

Most of the time, jQuery is used to add click event handlers to DOM elements, and there’s nothing wrong with this. In fact, jQuery is so helpful in this context, it’s hard to argue against using it for your event handling / delegation. But just be aware… there are other tasks that come up, and some of them can get rather messy. One example is replacing one DOM element with another. Now this may sound simple, but with vanilla JavaScript, this kind of work can get pretty tedious. Normally, I recommend learning how to do things with vanilla JavaScript that you would want to do with jQuery, but there are times when this kind of wheel reinvention becomes a bad idea.

So, this is where the jQuery replaceWith() method comes in; it allows you to chop out one piece of the page and replace it with another. You simply specify the original section of the DOM as well as the new chunk, and then jQuery takes care of all the work. And what makes this method so helpful is the expressive syntax; on a high-level, it’s a simple as A.replaceWith(B). You really do have to thank the folks from jQuery, for packing a great deal of abstraction into this one method. If you don’t believe me, go ahead and try this yourself using just vanilla JavaScript. I think you’ll find that it’s pretty tedious.

Example # 1

In example # 1, we have attached an event handler to the element with the id: “foo”. When clicked, that element is removed from the page, and replaced with a piece of markup defined in a string. Yes, it’s that easy, and there are certainly more interesting things you can do with this jQuery method.

Summary

Replacing one section of the page with another piece of markup is quite easy with the jQuery replaceWith() method. The syntax is very straight-forward and if you are already familiar with jQuery, there are quite a few possibilities.

Helpful links for the jQuery replaceWith method

http://api.jquery.com/replaceWith/

http://www.w3schools.com/jquery/html_replacewith.asp

http://stackoverflow.com/questions/730916/whats-the-difference-between-jquerys-replacewith-and-html

http://stackoverflow.com/questions/5248721/jquery-replacewith-fade-animate

Two Alternatives to the jQuery Document Ready Function for JavaScript

jQuery

jQuery Logo

There are two alternatives to document ready that are a bit easier to type

Most JavaScript programmers are familiar with jQuery’s document ready function. There is no doubt that it is a very helpful way to wrap your JavaScript with a cross-browser compatible function that will not run until the document has achieved a “ready” state. While the syntax is fairly simple, there are two slightly less verbose alternatives to the exact same functionality.

Example # 1

 

In Example # 1, we have the standard syntax for the jQuery document ready function.

Example # 2

 

In Example # 2, we omit the “document / ready” portion of the equation, and simply insert our function in the following expression $().

Example # 3

In Example # 3, we chain a jQuery ready() function to the return value of the jQuery object: $().ready(). So, when the jQuery object is ready, so is our code.

Summary

There is no doubt that the jQuery document .ready() function is super-useful. There is however, more than one way to invoke this functionality.

Helpful links for the jQuery document .ready() function

http://api.jquery.com/ready/

http://docs.jquery.com/Tutorials:Introducing_$(document).ready()

http://rpheath.com/posts/403-jquery-shorthand-for-document-ready

http://think2loud.com/653-jquery-document-ready-howto/

 

 

 

jQuery Under the Hood with Paul Irish

jQuery

jQuery Logo

If you’ve never poked around inside of jQuery, you should. Paul’s videos are a great way to get started

I decided to ring in the new year with two of Paul Irish’s videos that I had book-marked, but had not gotten around to viewing: 10 Things I Learned from the jQuery Source and 11 More Things I Learned from the jQuery Source.

In these two videos, you have Paul’s screen, so that you can follow his code, and a small sub-screen of his head while he talks, so that you can follow his hilarious commentary and thought pattern. My only complaint: there is so much good stuff here to dive into that it takes an hour to watch a 30 minute video because of the constant temptation to hit “pause” and then fire up JSFiddle and play around with the concepts that he discusses.

10 Things I Learned from the jQuery Source – YouTube

In general, exploring the un-minified version of jQuery is just plain ol’ good sense. There is a tendency to simply use jQuery and treat it as some magic black box that “just works, and works great…” But the fact of the matter is, there is only one thing going on inside of that giant self-executing function: JavaScript. That is it.

Everything that jQuery does for you, you could have done for yourself… but, jQuery is better, stronger and faster than the average bear. Fair enough. But, that does not mean that we should not lift up the hood, poke around and learn from the code inside… because what is going on in there is pretty dammed cool. The jQuery folks do things in some very interesting ways and there are tons (and I do mean tons) of neat stuff to learn from.

11 More Things I Learned from the jQuery Source – YouTube

Highlights of Paul’s videos include a brief discussion of jQuery’s “no conflict” feature,  his decision to hijack the .ready() method, and a hilarious discussion of how jQuery detects the presence of Internet Explorer (and the technique used is just so brilliantly creative that I had to once again pause the video, copy the code while squinting at the YouTube page, and try it in notepad myself… it just works).

If you are a JavaScript developer, you owe it to yourself to check out these videos. Paul Irish is pretty funny, and he is one of the top web developers out there. This combination makes all of his videos a pleasure to watch (and most importantly, to learn from).

Writing More Expressive and Readable jQuery Code with Method Chaining

jQuery

jQuery LogoYou can chain jQuery methods in a way that makes your code more readable, and allows you to be more expressive in the way that you traverse and manipulate DOM elements

Most of us are introduced to jQuery via the following scenario: when the user clicks an element, you want something to happen to that element. You Google the code, you copy the code, you edit the code so that it matches your DOM elements, it works, you are hooked, you add “jQuery” to your resume. An oft-told tale.

But, what about when the user clicks an element, and we want numerous thing to happen to elements that are in the neighborhood? Perhaps we want the parent element to turn blue, and then we want the <a> inside of the <span> that is a sibling to change it’s href attribute….etc. Sure, we can do all this using jQuery methods such as parent(), find() and end(). But the code starts to get a little verbose. One way in which we can write this kind of code in a slightly more elegant manner is by chaining method calls together. It makes the code more expressive and a little easier to read.

Example # 1

In example # 1, we query a specific selector, change its background color, use the parent() method to find the element’s parent, and then change the parent element’s background color to red. Pretty simple stuff. But, this code can be written better.

Example # 2 A

Example # 2 B

In example # 2 A, because $(this) returns a jQuery object, we can avoid further queries by simply “chaining” subsequent method calls. Chaining refers to using the return value of one method to kick off another method call, and so on. The concept is like that of a “chain reaction” in that one return value drives the call to the next method, and so on. In example # 2 B, we have the exact same code, but we break each of the “chained” methods calls to a new line, which makes the code even more expressive and easier to follow (comments have been added as well). JavaScript does not care about this white space, so you are free to organize your code in any way you like, which allows you to “express” your thoughts, or “logic” in a way that you feel works best.

This next example is a bit long, but what I wanted to accomplish was:

  • Provide full page markup so that you can copy the entire code, paste it into notepad and run the file, or use jsfiddle.net
  • Create an example where we chain methods together that walk up and then down the DOM, mutating multiple elements, without ever having to create another query

Example # 3

 

In example # 3, we use the jQuery parent(), find(), and end() methods to move up and then back down the DOM, mutating elements along the way, without ever having to write a second query. The next example is the exact same code, but heavily commented, to make it easier to follow-along.

Example # 4

 

In example # 4, we have the exact same code as example # 3, with comments added.

Summary

When a jQuery method returns a jQuery object, you can take advantage of that behavior by “chaning” subsequent method calls to the return value of the previous method. When using this approach, you can execute multiple DOM statements from the result of one query. The end result is code that is more expressive and easier to read.

Helpful links for chaining jQuery methods

http://ejohn.org/blog/ultra-chaining-with-jquery/

http://paulirish.com/2008/sequentially-chain-your-callbacks-in-jquery-two-ways/

http://forum.jquery.com/topic/jquery-method-chaining-returned-object-something-i-don-t-get

http://www.jquery-tutorial.net/introduction/method-chaining/