jQuery getScript Alternatives

JavaScript

jQuery getScript alternativesjQuery is aweseome, and the getScript even more so. But, consider some jQuery getScript alternatives in case you have to load a script file asynchronously without any help.

Today we’re going to talk about some jQuery getScript alternatives that you can use in your code. The jQuery getScript() allows you to get and execute external JavaScripts utilizing a type of AJAX HTTP GET request. Get requests can get any response, including JavaScripts, XML, and HTML, while getScript is limited to JavaScripts. The getScript method dynamically executes external JavaScript while Get receives data according to parameters.

The jQuery getScript Good

The Jquery getScript alternatives method is an extremely efficient way to load external code into your program at runtime. It allows us to write a piece of code once and use it in an unlimited amount of applications. We can also use code written by others in this way, and there is a vast amount of code snippets already available for you to use. If you are doing something common, like working with a form, you may not need to write any new code at all.

The jQuery getScript Bad

Unfortunately, any time you use external scripts, you will experience a slowdown as the program waits for the information to fetch. If you are using a code with a lot of external scripts, you will experience a reduced execution speed, especially if there are a lot of images loading as well.

You also need to load the jQuery library before you can access the getScript method. This extensive library will also slow down your code slightly, as it requires a download of a little under 250kb, depending on which version you are using.

The jQuery getScript Alternatives

Sometimes the code we are working on is not significant enough to warrant loading the entire jQuery library to access one or two external files, and in that case, we will need an alternative.

Let’s go step-by-step to arrive at a few Javascript getScript alternatives. We have created an object called myData, which has three properties. The properties of myData are FOO, BAR, and BAZ. We have placed this object in an external file at https://bit.ly/get-script-example, along with a console warning that tells us if we have successfully loaded the script. Let’s try to access this object from our code.

Example 1

In Example 1, we are asking the console to print out the properties of the object myData, but since we never tell the console where to find the object, the process fails and returns the error myData is not defined.

Example 2

In Example 2, we show you how we would typically access the myData object in the external file by using a jQuery getScript. You can see in this example that we first tell the code where to find the file.

As the file is downloading, it will come across the javaScript console warning and immediately print it to the screen. When it’s done loading, we use console.log to output the message that it has finished, and we use console.dir to display the properties of the object myData to the screen.

Example 3

In Example 3, we can see how to create a getScript function from scratch and eliminate the need for jQuery. The getScript function that we are creating takes two parameters, scriptUrl and callback.

We enter the scriptUrl directly as https://bit.ly/get-script-example, but our callback is going to be another function called onScriptLoad. The onScriptLoad function takes care of using the console to let us know that the script has loaded and to show us the properties of the myData object we saw in the last example.

Here’s what’s happening:

  • The getScript function creates a new script document element.
  • It assigns scriptUrl https://bit.ly/get-script-example as the source of the script and downloads the contents into the constant named script.
  • When the script named script finishes loading it calls the callback function onScriptLoad.
  • The onScriptLoad function uses console.log to tell us the script is loaded.
  • The onScriptLoad function uses console.dir to tell us the properties of myData.

Example 4

In Example 4, we show you two more ways to do pretty much the same thing we do in Example 3, but in a more precise way.

Example 4a

In the first part of this example, we show we can use an anonymous function as our call back instead of creating a separate named function for the task. This method allows us to embed the anonymous function in the calling statement and use one function and the calling statement instead of two functions and a calling statement. Fewer functions save us a bit of typing, and your code will be a little bit easier to read and follow.

Example 4b

In the second part of the example, we use an arrow function to take the place of the anonymous function and reduce the amount of typing necessary even further. This method is the preferred way to accomplish loading external scripts in most cases that do not use jQuery.

Conclusion

As you can see, you are not limited to using jQuery for loading external scripts into your program. In most cases, jQuery will be the answer because there is so much more you can do with it, and you are likely to take advantage of the library in many ways if you are developing a website or application. If you are doing something small, though, and there is no reason to load the library, you can take advantage of these examples to avoid using the library.

We hope that you have enjoyed reading over these examples and have learned something new. If these examples have improved your understanding and your coding skills, please share these jQuery getScript alternatives on Facebook and Twitter.

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.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.

Getting Started with Highcharts Part I: Basic Charts

JavaScript

Highcharts ChartLearn how to incorporate data visualization into your web page with just a few links of JavaScript

The data visualization trend shows no signs of slowing down, and charting is a key skill in that area. Highcharts is a jQuery plugin that provides a simple interface for creating great looking charts. There is a tremendous amount of muscle under the hood, which means that complex charts are not only within reach, but they do not require a degree in advanced mathematics. If you want to use Highcharts for a personal or non-profit project, then it is available without cost under the Creative Commons Attribution-NonCommercial 3.0 License.

In this article, I will cover the absolute basics of Highcharts. I will keep the deeper features for a later post, and instead focus on the bare minimum needed to leverage this super-powerful jQuery plugin and quickly spin up a chart on your web page.

Since Highcharts is a jQuery plugin, rendering a chart in your web-page could not be more simple:

So that’s it! Of course this little snippet of code has no use because highcharts knows nothing about the chart that we want to create. As simple as this library is to use, you do need to provide a few details so that Highcharts knows what to do. There are plenty of defaults that are provided so that you can worry about only the most critical details, but at minimum, Highcharts needs the data that powers your chart.

Example # 1A

Example # 1B

In Example # 1A, we have the base HTML for the rest of the examples in this article. For the sake of brevity, I will not include the HTML in further examples, only the JavaScript. Just keep in mind that the JS in the rest of the examples will go where you see the comment: “highcharts code will go here.”

In Example # 1B, we have the bare-minimum JavaScript needed to invoke the highcharts jQuery plugin. We passed an object to the highcharts method, which contains a “series” property. The value of this property is an array. There are multiple options when it comes to this series property, for now we will keep things very simple; the array has one element and that element is an object. This object has a “data” property whose value is an array. The element of that array has numbers, and the numbers in that array are the key to your chart.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1B: http://jsfiddle.net/u4wke4vo/1/

How to Demo:

  • Click the jsfiddle link
  • Change the data in the “series” property’s array and then click the “Run” button in the upper-left-hand corner of the screen to see how your changes affect the appearance of the chart.

X and Y Axis

Now it might be a good idea to take a moment to discuss the concept of the x and y axis. Although this article is focused on the absolute basics of Highcharts, there is little to accomplish here without a firm understanding of how data is represented visually. The “x” axis represents the horizontal dimension of the chart, and the “y” axis represents the vertical dimension. Another way of looking at this is: the “x” axis is the “left to right”, and the “y” axis is the “up and down”.

When you look at the jsfiddle link for Example # 1B, you’ll notice that the “x” axis doesn’t really offer too much value. What do the numbers 150, 900, 675 and 400 mean when they are mapped to an “x” axis of 0 to 3? For this article, I am using a “Total Sales” context so that each example will present the total sales for a group of three representatives of the Acme Widget Company. The “x” axis is the sales reps. So instead of displaying arbitrary numbers, the “left to right” dimension of our chart will display names of the sales reps.

Example # 2

Here in Example # 2, we’ve added a second property to the configuration object named “xAxis.” The xAxis property is an array of strings, and each string provides a label for the “x” axis. So, in our case, that “left to right” dimension of the chart represents the Acme Widget company’s sales representatives.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/u4wke4vo/2/

How to Demo:

  • Click the jsfiddle link
  • Change the data in the “series” property’s array and then click the “Run” button in the upper-left-hand corner of the screen to see how your changes affect the appearance of the chart.

Notice that Example # 2 is a line chart. That is the default chart type that Highcharts presents when you do not provide enough specifics. It looks nice, but it does not make a great deal of sense in this context because visually, it gives the impression of “data over time”. Our “Total Sales” context represents a series of set values for a year, so we need a chart type that better represents that kind of thought process. So, in my opinion, a column chart is a perfect example.

Example # 3

Here, in Example #3, we’ve added a new property to the configuration object called “chart”, which is an object. This object has one property: “type”. This is where you tell Highcharts whether you want a “pie” chart, a “bar” chart, or a “line” chart, etc. For our examples, a “column” chart makes much more sense than a line chart.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/u4wke4vo/3/

How to Demo:

  • Click the jsfiddle link
  • Change the data in the “series” property’s array and then click the “Run” button in the upper-left-hand corner of the screen to see how your changes affect the appearance of the chart.

You may have noticed that the chart’s title is: “Chart Title”, the “y” axis label is: “Values” and the “x” axis label is: “Series 1.” These are defaults that Highcharts provides when you have not specified them. While a helpful feature, it is likely that you’ll want to specify those kinds of labels. Let’s take care of that now.

Example # 4

So, now we’ve changed a few things in Example # 4. The “title” and “subtitle” properties are self-explanatory. The “yAxis” property is an object, whose “title” property is yet another object with a “text” property. This determines the label for the “up and down” dimension of our chart. The sole object in the “series” property’s array now has a “name” property. This provides the label for the “x” axis, or “left to right” dimension of our chart. In this case, it indicates that all sales figures represent sales in the United States only.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 4: http://jsfiddle.net/u4wke4vo/4/

How to Demo:

  • Click the jsfiddle link
  • Change the values of the various properties and then click the “Run” button in the upper-left-hand corner of the screen to see how your changes affect the appearance of the chart.

Summary

In this article, I covered the bare minimum needed to render a Highcharts chart in your web page. We covered the simple syntax for instantiating the jQuery plugin, and how to pass-in the configuration object. We also covered how to provide data, the x and y axis, and how to label them. We also discussed how to specify the type of chart that should be rendered.

Helpful Links for getting started with HighCharts

http://www.highcharts.com/

http://www.highcharts.com/docs

http://www.highcharts.com/demo

The JavaScript “this” Keyword Deep Dive: jQuery Click Handlers

JavaScript

JavaScript LogoLearn the difference between $(this) and “this” inside of your jQuery event handler.

In two previous posts, we learned that functions that are properties of an object are called “methods” (The JavaScript “this” Keyword Deep Dive: Nested Methods & The JavaScript “this” Keyword Deep Dive: An Overview). In this case, the JavaScript “this” keyword refers to the object that the method belongs to. Well, of course, this is usually pretty obvious from looking at the code.

But in an event handler, it may not be apparent to all that the JavaScript “this” keyword, is available to you inside of the event handler, and that it refers to the element that generated the event. Since many front-end developers are comfortable with jQuery, I thought I’d start with jQuery event handlers. And since click events are so common, let’s stick with that.

Example # 1

In Example # 1, we have created a click event handler using jQuery. When the user clicks the anchor tag inside of the element with the class: “download”, the jQuery “toggleClas” method is used to change the text “Click Me” fom red to blue.

Of course, many have seen $(this) used inside of the event handler to set a reference to the element that was clicked. It is helpful to know, however, that $(this) is an enhanced version of the JavaScript “this” keyword. That is to say: inside of the click event handler, “this” refers to the element that was clicked. When you put “this” inside of: $( ), you “wrap” the JavaScript “this” keyword with jQuery, which adds a number of properties and methods.

As a result of this “wrapping”, you can set a reference to the element that was clicked, but you can also leverage the power of jQuery. The native JavaScript HTML element does not have a “toggleClass” method, but jQuery does. So, by wrapping the JavaScript “this” keyword with jQuery, $(this) has allowed you to reference the clicked element, and use jQuery methods.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1: http://jsfiddle.net/9gZbE/

How to Demo: Click the text that says: “Click Me”. Each time you click that element, the text color will toggle between red and blue.

Example # 2

In Example # 2, we have changed the reference to the clicked element from $(this) to “this”. But when you click that element, there is an error in the JavaScript console. In Google Chrome, the error is: Uncaught TypeError: Object [object HTMLAnchorElement] has no method ‘toggleClass’, and in FireFox, the error is: TypeError: this.toggleClass is not a function. The reason for this error is that while the JavaScript “this” keyword can be used to reference the element that was clicked, it does not have a “toggleClass” method. So, an error occurs.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/9gZbE/1/

How to Demo: Open up your JavaScript console, and then click the text that says: “Click Me”. When you do, you will see an error indicating that the element you clicked does not have a “toggleClass” method.

Example # 3

So, in Example # 3, we continue to reference the element that was clicked by using the JavaScript “this” keyword, without the jQuery “wrapping”. That is: we are not using: $(this). The reason that the example now works, is because we are using the “classList” property of the element, and in-turn, the “contains”, “remove” and “add” methods. Consequently, this allows us to mimic jQuery’s “toggleClass” method.

It’s important to note that although we used jQuery to create the click handler, we can still use the JavaScript “this: keyword inside of that event handler, and access the native JavaScript element object.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/9gZbE/2/

How to Demo: Click the text that says: “Click Me”. Each time you click that element, the text color will toggle between red and blue.

Summary

In this article, we learned about the JavaScript “this” keyword when used inside of a jQuery event handler. We learned that we can “wrap” that keyword with jQuery, leveraging that library’s DOM manipulation methods. We also discussed how inside of a jQuery event handler, we can still use the “un-wrapped” version of “this”, and leverage native JavaScript DOM manipulation methods.

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/

Cross-Browser Asynchronous JavaScript Script Loading

Asynchronous

JavaScript LogoWhile it is perfectly normal to have one or more JavaScript tags in your markup as prerequisites to your code, there may be situations in which you want to avoid this

When I build a piece of functionality that is contained in one JavaScript file, I try to avoid asking the back-end developer to include additional scripts in the markup. So, my philosophy is: my script provides a certain “chunk” of functionality. Whatever external resources my script depends on are my script’s problem and will be handled accordingly. As often as possible, I’d like the consumer to simply choose to use or not use my script. This decision should involve simply adding or removing my script from the markup. The remaining abstraction is my responsibility.

This may seem a bit altruistic, but so far I’ve never had to lower my standards on the issue. The key to keeping this philosophy is, of course, the ability to reliably load other scripts asynchronously. I say “reliably” because it’s not enough to simply inject the script into the head of the document. You need to know when that script has successfully loaded before you take further actions that depend on the script.

The good news is: modern browsers provide the “onload” event, allowing you to set up your handler without too much effort. But the bad new is: Microsoft’s Internet Explorer 8 and below do not implement that event. So, there is some work to do. It’s not too bad; it just means we need to fork our code a bit.

Oh, and by the way; you might be wondering why I didn’t simply use the jQuery.getScript() method. jQuery is awesome and we all love it more than coconut ice cream. But I strongly believe that it’s important to know how to do these things with native JavaScript. One day a client will tell you that for whatever reason, you can’t use jQuery. When that day comes, you’ll be ready.

So let’s have at it!

Example # 1

Now here in Example # 1, we’ve created a function that takes a URL and a callback as arguments. The URL is required, the callback is optional. As you can see, this is pretty straightforward stuff:

  1. Create a script DOM element
  2. Assign an anonymous function to the “onload” event
  3. Set the script’s source
  4. Inject the script into the DOM

No worries.

Example # 2

In Example # 2 we have rolled up our pant legs and stepped into the cold wet mud that is Internet Explorer 8 (and below). So here we will need to assign that same anonymous function to the script element’s “onreadystatechange” property. And this property will change as the “ready state” of the script element updates. When that ready state is “loaded”, then we can be confident that the external script has successfully loaded and executed. It’s a bit more work, but then again, Internet Explorer wouldn’t be such a charming little browser if it adhered to the same kind of common-sense standards as every other modern browser on the planet… but I digress.

Example # 3

Well… Example # 3 certainly contains a bit more code, huh? In fairness, it’s heavily commented. But outside of that, what has happened is that as promised, we’ve forked the code so that we can support good ol’ IE, as well as all the other browsers that are made by sane people. I chose to check for the existence of document.attachEvent as a way of sniffing the browser. Some may disagree, but for me, it has always worked just fine.

If you follow the link to the full working example below, be sure to open your JavaScript console. When you do, you’ll see that the message from the actual external script always fires before the callback. Always. This is what we needed: the ability to load the script, and reliably know when it has loaded so that we can safely assume whatever resources it provides are available to us. So go ahead and try it in Internet Explorer 8 or Internet Explorer 7; it works just fine.

The full working example can be found here: http://examples.kevinchisholm.com/javascript/script-loading/

Summary

In this article, we learned how to implement a reliable solution for cross-browser asynchronous JavaScript loading. We discussed the need to fork our code in order to support Internet Explorer 8 (and below), and the “onreadystatechange” event that it implements.

Helpful Links for JavaScript loading

http://css-tricks.com/thinking-async/

http://friendlybit.com/js/lazy-loading-asyncronous-javascript/

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

 

Getting Started with JavaScript Unit Testing and jQuery QUnit

JavaScript

JavaScript LogoDecent programmers tests their code before deploying it. In JavaScript development, this usually means viewing the web page that your code interacts with, and clicking one or more elements in the page to ensure that the desired result is achieved

When your code base starts to grow and become more complex, testing can become tedious. Even worse, manual testing can become unreliable, because you not only have to test your new code, you have to regression test as well, so that you can be sure your new code did not break any old code.

Yuck!

If we’ve learned nothing else at this point in technology, we have at least discovered, first hand, that humans are really bad at tedious, repetitive tasks. Fortunately, computers love this kind of work.

Enter Unit Testing

The key to writing testable code is to produce small modules of functionality that always return a predictable result.

Unit testing provides a methodical way to ensure that your code always performs as expected, and provides red flags for the nanosecond that this condition changes. The key to writing testable code is to produce small modules of functionality that always return a predictable result.

jQuery QUnit

jQuery QUnit is a test framework created by the same impressive folks who bring you jQuery. It is lightweight, easy to understand, and easy to use. It has a number of simple methods that allow you to test your code. What is really impressive about jQuery QUnit is that it is designed to run in a (very) simple web page so that your test results are not only visual, but easy to understand.

Before we dive into the code, it might help to take a look at the full working example:

http://examples.kevinchisholm.com/javascript/unit-testing/qunit/part-i/

Let’s review the files involved in the full working example.

qunit.js

This is the QUnit JavaScript library.

qunit.css

This is the CSS that our test page will need.

tests.js

This is the JavaScript file that contains our unit tests.

index.html

This is the web page that you see in the full working example. It allows us to view the test results.

Here is the full source code for index.html:

Example # 1 A

In Example # 1A, we test a function named “badFunction”. I gave it that name because when we test for a positive result, it fails. The syntax is simple:

  • We execute the test() method
  • The first argument to the test() method is simply a label for the test that makes it easier to identify in the test results page (index.html).
  • The second argument to the test() method is an anonymous function. We craft our test(s) inside of this function.
  • Inside of the anonymous function, we execute the ok() method, a boolean assertion. This test passes if the first argument is “truthy”.
  • The first argument to the ok() method is the execution of badFunction(). Since badFunction returns false, the test fails.
  • The second argument to the ok() method is the test result message.

Example # 1 B

In Example # 1B, The approach taken is identical to Example # 1A, with one exception: we test goodFunction(), which passes the ok() test because its goodFunction() returns true.

Example # 2 A

In example # 2A, we test the function makeArray1(). That function returns an empty array literal. Our unit test consists of two calls to the ok() method. The first call simply checks to see that makeArray() returns a true array. It does, so that test passes. The second call to ok() checks to make sure there is at least one element in the array. The array is empty, so that test fails.

Example # 2 B

In Example # 2B, we test makeArray2(). Since that function returns an array with three elements, both calls to the ok() method pass.

Example # 3 A

In Example # 3A, we test a function named lessThanFive(). It is actually a closure that returns a function. The closure allows us to have a private scope which will keep track of how many times the function has been executed. Since this function was designed only to be executed less than five times, on the fifth execution, and for every execution that follows, the function returns false. The first four times, it will return true. You’ll see in the full working example that our unit test passes four times and then fails twice. This is because the first four times that lessThanFive() runs, it returns true. The fifth and sixth times that it is run, it returns false.

Example # 3 B

In Example # 3B, we have a slightly more elegant approach. Instead of writing out six calls to the ok() method, we have a FOR/LOOP, which executes six times. On each iteration, it calls the ok() method, which, in turn, executes the lessThanFive() function. The only drawback to this approach is that we do not have a nice customized test message for each iteration of the test.

Once again, here is the full working example:

http://examples.kevinchisholm.com/javascript/unit-testing/qunit/part-i/

Summary

In this article, we took a brief look at how to write JavaScript unit tests using jQuery QUnit. We learned about the files needed, the test() method, and the ok() method. We learned how to check for more than one possible outcome of a test, and that there is more than one way to write the same test.

In the next article, we’ll take a closer look at the other features of QUnit.

Helpful Links for jQuery QUnit

http://qunitjs.com/

https://github.com/jquery/qunit

http://en.wikipedia.org/wiki/QUnit

http://net.tutsplus.com/tutorials/javascript-ajax/how-to-test-your-javascript-code-with-qunit/

http://msdn.microsoft.com/en-us/magazine/gg749824.aspx

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