How do I use the jQuery.css() Method?

jQuery

Angular logo - cssThe jQuery CSS method allows you to style one or more DOM elements

Let’s begin with the HTMLElement.style property, which provides the access you need to style any DOM element. As a front-end web developer, you should make it a point to be familiar with this low-level DOM API. But the HTMLElement.style property comes with challenges, the two biggest being:

  1. The syntax is verbose, which leads to repetitive, boilerplate code.
  2. You cannot overwrite the HTMLElement.style property, which means that you cannot arbitrarily assign an object to it.

Now while it may seem like a minor detail that you cannot overwrite the HTMLElement.style property, this limitation does negate the ability to assign a well-crafted object to an HTMLElement’s style property. It also severely minimizes code re-use.

But the jQuery CSS method provides a powerful way to sidestep the quirky limitations of the HTMLElement.style property. It offers the ability to style DOM elements in a way that is considerably more elegant and expressive.

For one thing, the syntax is based on method chaining; you chain the css() method to the result of any jQuery query. So whether your query returns one or many elements, the style property and value that you pass to the css() method will be applied to the element(s) returned by your query. And in addition to a more concise syntax, there is the potential for code reuse. And finally, something that is often overlooked about this method: you are styling the DOM element directly (as opposed to using an external style sheet). As a result, the styles you apply will enjoy a high specificity.

In its most basic form, the jQuery.css() method takes two arguments. Both arguments are strings. The first argument is the name of the CSS property that you want to change. The second property is the new value for that CSS property. When you execute the CSS method against one or more DOM elements, jQuery adds a style attribute to each DOM element. And then, jQuery uses the second argument you provided as the value for that CSS property.

Try it yourself !

In the above example, there are five paragraph elements. Click each paragraph. When you do, you’ll see that each clicked element turns red. Click the JavaScript tab. In the JavaScript code, you’ll see that there is a click-event handler set up for each paragraph element. As a result, when any paragraph is clicked, jQuery executes the CSS method against that paragraph. Two arguments are passed to the CSS method. The first argument is color, which is the CSS property that we want to change. The second argument is red, which is the new value for that CSS property.

So, the approach taken so far is a very simple implementation of the css() method. In this case, we are passing only two strings. These two strings act as key/value pairs for the specified style property. But it is also possible to pass an object to the css() method. Significantly, this approach allows you to style multiple properties of an HTMLElement. This, of course, is an advanced implementation of the css() method, which I’ll cover in another article; for now, it’s just good to be aware of it.

Summary

So once you’ve had a chance to work with the css() method a little, I think you’ll agree that it is arguably one of the most genius features of jQuery. It frees you from two limitations of the HTMLElement.style property, and in addition to the elegant syntax, this method provides a way to re-use well-crafted code, in order to style multiple DOM elements. And if you look into the advanced syntax, you’ll see that multiple styles can also be applied within one call to the css() method.

jQuery fadeOut (advanced)

jQuery

fadeoutThe jQuery fadeOut method can take multiple arguments. You can set the duration, easing and also provide a completion callback

Hiding DOM elements is certainly a common task for any front-end
web developer, and the jQuery.fadeOut() method allows you to not only hide an element, but it allows you to animate this action as well. Now, while fading out can elevate the user experience, it would be nice for the web developer to have some control over that. Well, fortunately, the jQuery.fadeOut() method provides just that. With some advanced features that allow you to determine the duration of the animation and the easing effect, it controls the “feel” of that animation. In other words, we don’t just want to move an object from point A to point B; we want that motion to mimic the way objects move in the real world. We can also pass a callback function to the jQuery.fadeOut() method that allows us to act upon the successful completion of the fading out of that DOM element. Now, while you may not always need to take advantage of this feature, it certainly is pretty important to know about it. The thing is, the ability to reliably act upon the successful completion of an animation is a business requirement that comes up more often than many may think.

There is somewhat of a fuzzy line between the jQuery hide, fadeOut and animate methods. At the end of the day, they all leverage jQuery animation. With the fadeOut method, if you pass no arguments, then the matched elements are faded-out with a duration of 800ms(0.8 seconds). But if you want to gradually fade-out the elements, then you can specify a custom duration, the easing and a callback for when the fadeOut method completes.

Try it yourself !

In above example, click the button labeled: “Fade the paragraph out”. You will notice that the paragraph fades out slowly. The second button simply refreshes the page so that the example can easily be run over and over.

Now click the HTML tab. You’ll see an embedded stylesheet (the style element). There we define the .done class which states that any element with that class has a green background and white text. When  you run the example code, you’ll notice that after the animation completes, the button changes to green background with white text.

Now click the JavaScript tab. There is a click event handler for the element: button#fadeOut. When that button is clicked, the jQuery fadeOut method is called on every paragraph element in the page (in this case, there is just one).

Notice how there are three arguments passed to the jQuery fadeOut method . The first argument is the duration property, which is set to: 2000. This means that the fading-out of the paragraph should last 2000 milliseconds, or two seconds. The second argument: “swing”, is for the easing. It makes the animation a bit more lifelike. The third argument is a function. This callback function will be executed when the fade-out completes. Inside of that function, we change the text of the button to “Fade-out complete!”. Also, we add the class “done”.

jQuery fadeIn (advanced)

jQuery

fadeinThe jQuery fadeIn method can take multiple arguments. You can set the duration, easing and also provide a completion callback, which allows you to execute tasks which rely on the completion of your fade-in animation.

There is somewhat of a fuzzy line between the jQuery show, fade-in and animate methods. At the end of the day, they all leverage jQuery animation. With the fadeIn method, if you pass no arguments, then the matched elements are faded-in with a duration of 800ms (0.8 seconds). But if you want to gradually fade-in the elements, then you can specify a custom duration, the easing and a callback for when the fadeIn method completes.

Try it yourself ! – Example # 1

In above example, click the button labeled: “Fade the paragraph in”. You will notice that the paragraph fades in slowly. Now click the HTML tab. The paragraph element has its style attribute set to: “display: none;”. This is the reason that that the paragraph is not visible when the page loads. Now click the JavaScript tab. There is a click event handler for the element: button#fadeIn. When that button is clicked, the jQuery fadeIn method is called on every paragraph element in the page (in this case, there is just one).

PARAGRAPH – A

Try it yourself ! – Example # 2

Notice how there are three arguments passed to the jQuery fadeIn method . The first argument is the duration property, which is set to: 2000. This means that the fading-in of the paragraph should last 2000 milliseconds, or two seconds. The second argument: “swing”, is for the easing. It makes the animation a bit more lifelike. The third argument is a function. This callback function will be executed when the fade-in completes. Inside of that function, we change the text of the paragraph to “Fade-in complete!”. Also, we add the class “done”. If  you click the HTML tab again, you’ll see an embedded stylesheet (the style element). There we define the .done class which states that any element with that class has a green background and white text. When  you run the example code, you’ll notice that after the animation completes, the paragraph changes to green background with white text.

jQuery show (advanced)

jQuery

jqueryshowThe jQuery show method can take an object as an argument. In that argument, you define one or more properties that give jQuery more detail on how you want the matched elements to become shown

There is somewhat of a fuzzy line between the jQuery show, fade-in and animate methods. At the end of the day, they all leverage jQuery animation. With the show method, if you pass no arguments, then the matched elements are immediately shown. But if you want to gradually show the elements, then you can provide an object that gives configuration details.

Try it yourself !

In above example, click the button labeled: “Show the paragraph”. You will notice that the paragraph fades in slowly. Now click the HTML tab. The paragraph element has its style attribute set to: “display: none;”. This is the reason that that the paragraph is not visible when the page loads. Now click the JavaScript tab. There is a click event handler for the element: button#show. When that button is clicked, the jQuery show method is called on every paragraph element in the page (in this case, there is just one).

Notice how there is an object passed to the jQuery show method. That object provides details on how we want the paragraph element to be shown. The duration property is set to: 2000. This means that the showing of the paragraph should last 2000 milliseconds, or two seconds. The complete property is a function. This callback function will be executed when the animation is complete. Inside of that function, we change the text of the button to “Animation complete!”. Also, we add the class “done”. If  you click the HTML tab again, you’ll see an embedded stylesheet (the style element). There we define the .done class which states that any element with that class has a green background and white text. When  you run the example code, you’ll notice that after the animation completes, the button changes to green background with white text.

jQuery.off()

jQuery

jquery offWith the the jQuery off method, you can unbind handlers for one or more events, for each matched element.

Most of the time, front-end web developers are concerned with binding event handlers — that is, defining a JavaScript function that will be executed when an event occurs. An event can be a mouse click, a hover, a scroll, or just about any other action that a user takes on the page. And it goes without saying that jQuery makes event binding easy. But what about when you want to remove an event binding? There may be cases in which, for whatever reason, you no longer want your event handler function to be executed. This does happen.

Well, a typical scenario might be when a user is not authenticated, in which case you may want to prevent the user from taking certain actions. Or, perhaps you have a business requirement that involves displaying an advertisement after the user has advanced a slide-show a certain number of times. Well, part of that requirement might be that the ad has to show for at least 10 seconds, and during those ten seconds, you do not want the user to be able to click the “back” or “next” buttons in the slide show.

The jQuery.off() method allows you to remove an event handler that was bound using the jQuery.on() method. The syntax requires that you pass a string as the first argument, and that string that you pass to the jQuery.off() method specifies the event that you want to unbind. For example, you may have bound event handlers for both the “click” and “dblclick” events and you may only want to unbind the “click” event handler but leave the “dblclick” event handler intact. But just remember: you can only unbind event handlers that are managed with jQuery.

Try It Yourself!

In the above example, there are three paragraph elements. Click each one. When you do, you’ll see the text change to: “I was clicked”. Next, click the “Refresh” button so that the page reloads. Now click any of the paragraphs. You’ll notice that the text no longer changes as you click each one.

Click the JavaScript tab. You’ll see that there is a click-event handler for each paragraph. This changes the text to “I was clicked” when a paragraph is clicked. There is also a click-event handler for the first button. When that button is clicked, the jQuery off method is called against every paragraph in the page. This unbinds every click event handler. Thus, when you click any paragraph, the text no longer changes.

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/FEV-jq-off

Summary

While jQuery makes event binding simple, that is also the case when you need to unbind one. The jQuery.off() method is used to remove an event handler from one or more HTML elements. So, when you pass a string as the first argument, you simply let jQuery know which event you wish to unbind. The one restriction of the jQuery.off() method is that it can only be used with event handlers that are managed with jQuery.

How do I fetch JSON data with jQuery?

jQuery

jquery-logo jQuery’s ajax method provides a way to make an HTTP request for JSON data and then handle the successful result.

Assuming that you have access to jQuery in your web page, fetching JSON data is very simple. The key to this is the jQuery.ajax method. This method takes an object as its first argument. In this object, you can, at minimum, specify url and success properties. The url property is the web address of the JSON data that you want to fetch. It should start with http:// or https://. If the resource is a relative path, then it could be virtually anything, for example: /data/json/customers. The success property is a method. That is, you assign a function to the success property. This function will receive the fetched JSON data as its first argument. Inside the function, you can process that data.

Try it yourself!

See the Pen jQuery AJAX – Basic Example by Kevin Chisholm (@kevinchisholm) on CodePen.

In the above example, we make a call to $.ajax. We pass an object to this method and that object has two properties. The url property has the web address of the JSON data that we want. Notice that this address ends with: ?sleep=2. This just means that for demonstration purposes, we can force the request to be delayed for two seconds. Go ahead and change that to ?sleep=5. You will see that the request then takes five seconds to complete. If you change it to ?sleep=0, then you will notice that the request completes very quickly. Either way, you can control this request and slow it down in order to see more clearly how things work.

The success property has an anonymous function assigned to it. This function will be executed once the $.ajax requests succeed. The function will take the fetched  data as its first argument. So, inside this function we use the JSONView jQuery plugin to inject the JSON data into the DOM.

Important note: we haven’t specified the HTTP verb that will be used for our request. For example, GET and POST are common HTTP verbs used for sending or receiving JSON data, but PUT and DELETE are fairly common as well. The jQuery.ajax method allows us to specify the HTTP verb that should be used for the request, and we specify this HTTP verb in the object that is passed to the jQuery.ajax method. Note that by default, the jQuery.ajax method will make a GET request, unless we specify a different verb, such as: type=”POST”, for example.

So, in the above example, we specified a success method.
It’s important to note, however, that we did not specify an error method. The reason for this was to make the example code easy to follow. However, it is highly recommended that you always provide an error handler when making any HTTP request. Keep in mind that while you may have full confidence in the requests you are making, HTTP transactions are fragile by nature, and in theory anything can happen. So, whatever you do, don’t overlook this small but important detail.

How do I move DOM elements with jQuery ?

jQuery

jquery-logo - appendToThe jQuery.appendTo method makes it easy to move a DOM element. You won’t need to be concerned with creating or destroying elements and event handlers are preserved.

Moving DOM elements using vanilla JavaScript can be a bit tedious. It’s certainly possible, and it is a good idea to understand the steps, but it does require more code. jQuery provides powerful abstraction for this task, however, and the amount of code needed is minimal.

Whenever possible, I favor using vanilla JavaScript to solve a problem, because leaning on jQuery too much can weaken your overall JavaScript skills. In this case, however, I recommend letting jQuery do all of the work for you. The main issue with vanilla JavaScript when it comes to moving DOM elements is the need to understand the intricacies of the low-level hierarchical DOM API. For example, you’ll need to get ahold of the parent element of the DOM node, after which you’ll want to move your target element. Frankly, I commend anyone who wants to take on this challenge, but in many cases, it just makes sense to leverage jQuery.

Try it yourself !

See the Pen Moving DOM elements with jQuery by Front End Video (@frontendvideo) on CodePen.

In the above example, click the “HTML” tab. There are two DIVs with the IDs: “left-list” and “right-list“. DIV#left-list has an unordered list with the days of the week, and DIV#right-list is empty. Now click the “JS” tab. You’ll see that there is a click-event handler for $('#left-list li'). This means that when any of the list items are clicked, the anonymous function you see will be executed.

Go ahead and click each of the days of the week and you’ll see that it is moved to the DIV#right-list element. After each element is moved, if you click it, nothing happens.

In the anonymous function, we use the JavaScript this keyword to reference the element that was clicked. Actually, we wrap the JavaScript this keyword with jQuery: $(this). We then chain the .appendTo method, and pass it a target element: .appendTo( $('#right-list') ). Here we are telling jQuery: “Move this element to the #right-list element, and make it the last child“. So, we are appending it to DIV#right-list. We then chain this: .unbind('click');. The reason we do that is: the jQuery appendTo method retains any event bindings for elements that are moved. Most of the time, this is probably what you want. But in this case, we do not want the event bindings to travel with the element because once a list item is moved inside of the #right-list element, we no longer want it to have a click-event handler. But that is simply for this example.

Summary

Simply put, moving DOM elements with vanilla JavaScript can be messy business, but the jQuery.appendTo method provides abstraction that simplifies this process. Instead of having to dig into the low-level DOM API, you can simply specify the source and target HTML elements. In other words, you let jQuery know which element you want to move, and which element you want to append it to. In cases such as these, it’s often best to let jQuery do all of the work for you. It will certainly minimize the amount of boilerplate coding you’ll have to do, and will help to keep your JavaScript easier to manage.

jQuery.filter()

jQuery

jquery-logo jQuery can return one, or multiple HTML elements in the matched set. jQuery.filter() reduces the elements in that matched set, based on a criteria that you provide.

Most front-end web developers understand that jQuery literally queries the DOM, and returns a set of elements that match the CSS-like text string that you pass to the jQuery function (AKA: “$()“). But what if you want to further refine that query? Using jQuery.filter(), you can tell jQuery things such as: “Filter out the ODD elements”, or “Filter out the elements that have the word “automobile” in their text”, and so on.

One of the things that makes the jQuery.filter method so powerful, is that you can not only pass a string to it, but also a function. Passing a function allows you to write code that programmatically tells jQuery exactly how  to reduce the matched set. See Examples # 2 and # 3 below for more information about passing a function to the jQuery.filter method.

Example # 1

See the Pen jQuery.filter Basics – Part 1 by Front End Video (@frontendvideo) on CodePen.

In Example # 1, we have an unordered list that contains the seven days of the week. We want to apply some custom styles to only the even elements returned in the query. So, we use jQuery.filter(). We pass the string “:even” to jQuery.filter, which tells this method to return only the even elements (that is, element # 0, element # 2, element # 4, element # 6, and so on). As a result, only the days Monday, Wednesday, Friday and Sunday have the custom style applied. This is because the jQuery.filter method filtered the matched set down to those elements only, and returned a new set of only those elements. We then chained the .css method to that set, and applied the class “styled“, which adds some padding and the background-color: #FFB347.

Example # 2

See the Pen jQuery.filter Basics – Part 2 by Front End Video (@frontendvideo) on CodePen.

In Example # 2, we pass a function to the jQuery.filter method. In this function, we use the JavaScript modulus operator, telling jQuery that we only want every 5th element in the matched set. As a result, every 5th item in our unordered list has the custom styles applied. Don’t be misled by the simplicity of this example. Passing a function to the jQuery.filter method provides a tremendous amount of power. In this case we simply indicated that we wanted every 5th element, but because we are using a function, the code you write in order to filter out the matched set is limitless.

Example # 3

See the Pen jQuery.filter Basics – Part 3 by Front End Video (@frontendvideo) on CodePen.

In Example # 3, we once again pass a function to the jQuery.filter method. In this case, we tell jQuery that we want to reduce the matched set down to only the elements whose text is less than six characters. As a result, only the word in the list with five characters or less have the custom styles applied. Play with the example code yourself. For example, change this: return $(this).text().length < 6; to THIS: return $(this).text().length < 8;. Notice how the number of list items with custom styles changes. This is because you have changed the criteria passed to the jQuery.filter method by changing the code in the function.

Summary

When you query the DOM, When jQuery returns one, or multiple HTML elements in the matched set, so depending on how you organize your code, you may want to further refine that matched set. The jQuery.filter() method allows you to determine how that matched set is further refined, and what makes the jQuery.filter() method so powerful is the fact that the argument you provide can be as simple as a string, or as complex as a function. Passing a string is surprisingly flexible, and passing a function provides exponential power, as you can programmatically determine the result set that the filter will return.

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/