JQuery Ajax (Best Tutorial 2019)

Ajax with jQuery

Ajax with jQuery

Ajax, which stands for Asynchronous JavaScript and XML, lets us fetch and send data to and from a server asynchronously, in the background, without interfering with the user’s experience.

 

The most common format for getting data back is now JSON, or JavaScript Object Notation; before you start fetching data, you’ll become familiar with this format. Next, you’ll look at some sample JSON and see how to work with it using JavaScript.

 

Then, you’ll be introduced to jQuery’s ajax() method. Finally, you’ll use a real-world third-party API to pull in data and display it on a page. To do this, you’ll need to explore JSONP, a method of requesting data from third-party web sites.

 

Ajax has been somewhat of a buzzword in recent years, but what it actually means can be confusing. It’s simply a way of asynchronously fetching data. That’s it.

 

JSON

The “x” in Ajax may stand for XML, but the format nearly everyone prefers these days is JSON, which stands for JavaScript Object Notation (JSON).

JSON data looks very similar to a regular JavaScript object. Here’s an example:

"name":"Jack Franklin",
"age":20,
"location":"London, UK",
"friends":[
"Grant",
"Jamie",
"Dan",
"Richard",
"Alex"
]
}

 

There are two important things to note here. The first is that, unlike JavaScript, keys in a JSON object have to have double quotes around them. For example, in JavaScript, all of the following are valid:

var jack = { "age": 20 };

var jack = { 'age': 20 };

var jack = { age: 20 };

However, only the first line would be valid in JSON.

Values in JSON can be of the following types:

  • String
  • Number
  • Array
  • Boolean true/false
  • null

 

Items in arrays can be any of these types, too. Strings need to be double quoted, but the rest don’t:

{

"num":2,

"decimal":2.5,

"boolean":true,

"array":[1,2,3,true,null]

}

 

Much like JavaScript objects, key-value pairs need a comma after them, unless it’s the last pair in the object.

All current browsers come with native JS methods for parsing JSON. There are two main methods:

JSON.stringify(): Takes a JavaScript object and produces a JSON string from it.

JSON.parse(): Takes a JSON string and parses it to a JavaScript object.

The Can I Use web site (Can I use JSON parsing) shows all current browsers now natively support JSON.

 

Parsing JSON in JavaScript

Start with a basic JSON string:

var json = '{ "person" : { "age" : 20, "name" : "Jack" } }';

 

Right now, all JavaScript sees here is a string. It doesn’t know it’s actually JSON. You can pass it through to JSON.parse() to convert it into a JavaScript object:

var parsed = JSON.parse(json);
console.log(parsed);
This gives you:
{ person: { age: 20, name: 'Jack' } }
It is now a regular JavaScript object and you can access properties, just as you’d expect, using either notation:
console.log(parsed.person);
console.log(parsed.person["age"]);
This gives the following:
{ age: 20, name: 'Jack' } 20
If you get the JSON wrong, you’ll see an error. Take the following invalid JSON, for example:
var invalid = '{ person: "Jack" }';
It’s invalid because the key, person, should have quotes around it. Trying to run JSON.parse(invalid)
gives this result in Google Chrome (other browsers may show a slightly different error message):
SyntaxError: Unexpected token p
This is easily fixed, as follows:
var invalid = '{ "person": "Jack" }';
You can do the opposite and turn an object into a string:
var json = {
person: {
age: 20,
name: "Jack"
}
}
console.log(JSON.stringify(json));
This gives you a string containing the following:
{"person":{"age":20,"name":"Jack"}}

 

When working with JSON responses from a jQuery Ajax call, you’re not going to have to worry much about parsing the JSON. jQuery takes care of that for you.

 

Ajax with jQuery

Ajax with jQuery

jQuery comes with jQuery.ajax(), a complex and powerful method to handle Ajax requests (http://api. http://jquery.com/jQuery.ajax/). This method is different from others you’ve seen because you don’t call it on a jQuery object containing elements, but on the jQuery object itself. Most methods are called on sets of elements; for example:

$("div").addClass("foo");

This calls the addClass() method on every element within the jQuery object $("div"), which is all the div elements on the page. With the $.ajax() method, however, you simply call $.ajax(...)

 

Take a look at how you might make a request to a fictional URL to get some JSON. Later on, you will use an actual API, but for now, familiarize yourself with the method.

 

With the $.ajax() method, you can pass in one argument, which is an object of options, or you can pass in two arguments. The first is the URL to pass in and the second is an object of options. We prefer the first method—passing in one object that contains a property for the URL, in which you would either do, for example:

$.ajax({

"url": "/myurl",
//more settings here
});
or
$.ajax("/myurl", { ... });

 

We prefer the first method because we think it’s clearer to have every option within one object and to have each option on its own line. Hence, this is the style we’ll use throughout the blog. It’s also the one we see most others use, which is another good reason for following suit. If you prefer the other syntax, however, feel free to use it.

 

The most important argument is the URL, which may be a local URL (on the same domain as your script) or an external URL (hosted on a different domain). There’s a bit more work to be done if you want to use an external URL, so for now, presume it’s a local URL that will return data in JSON format. You’ll get to external URLs later.

 

The URL is relative to the page that the script is loaded into. This can vary depending on your site structure, so the best way to be confident which URL the script will hit is to make it an absolute URL—that is, put a “/” at the beginning so that the URL is relative to the domain root.

 

The list of properties that can be set has grown over the years. Refer to the documentation (jQuery API Documentation) for the full list.

Here we will outline a few important properties to illustrate how to use jQuery to make a request from the server.

 

After adding the URL you can also add type. This is the type of request to make. The default is GET, which is when you’re making a request to get the data from the URL. The other is POST, which is when you want to send (or post) data to the server.

 

Next up is dataType, which denotes the type of data that is returned to you. jQuery is pretty clever here because it is able to fairly accurately guess, but we like to be explicit and set the dataType, nearly always to “json”. In order to see the success or failure of an Ajax call, you can chain the done() or fail() methods:

 

$.ajax({
"url" : 'https://jsonplaceholder.typicode.com/posts' }).done(function(data){
//if the call is successful
console.log(data)
}).fail(function(jqXHR, textStatus, errorThrown){ //if the call is not successful
}).always(function(){
//runs all the time
});
done(), which replaces success()
fail(), which replaces error()
always(), which runs regardless of whether the request was successful or not

 

It’s important to again note that Ajax calls are asynchronous. When something is asynchronous, it runs in the background and it doesn’t stop the rest of your code from executing. This is also known as nonblocking.

 

Running something asynchronously makes it nonblocking because it doesn’t stop the code below from executing. Something basic like a call to console.log is blocking because while it’s running (albeit for a fraction of time), nothing else can run until it’s finished.

 

When you make an Ajax request, the code immediately after the Ajax request code is run, regardless of whether or not your Ajax call has finished. When you looked at animations in blog, you had to use callback functions because the code below the animation would run immediately.

Animations are also asynchronous, and just as you used a callback with animations, you can do so with Ajax.

 

Thus, you can’t just return your data within the function, because when the Ajax method is called, the data will take an arbitrary amount of time to get back to you, and it’s happening while your other code is executing.

 

Hence, you chain the function that you know will run only once you have the data. This is much like the callbacks you used in animating elements, which you knew would only run once the animation had finished.

 

Put all this together into an example. As always, get an index.html page, which for this example should just contain the following:

<!DOCTYPE html>
<html>
<head>
<title>blog 08, Exercise 01</title>
<script class='lazy' data-src=jquery.js></script>
<script class='lazy' data-src=app.js></script>
</head>
<body>
</body>
</html>

 

There’s no need for any actual HTML elements or a style sheet. Next, create a file called sample.json. This will contain some JSON, which you will fetch via an Ajax request. Put the following inside it:

"people": [

{ "name": "Jack", "age" : 20 },
{ "name": "Grant", "age": 21 },
{ "name": "Lisa", "age": 21 }
]
}

 

That’s a JSON object that contains an array of people with age and name properties. Implement the Ajax call in your app.js file. Notice how the following uses a url of /sample.json. This means the JSON file must sit within the project root directory. If it doesn’t, or if you’d rather put it in a subdirectory, amend this.

$(function() {
$.ajax({
"url": "/sample.json",
"type": "get",
"dataType": "json",
}).done(function(results){
console.log(results);
});
});

 

Setting Up a Local Development Server

server

Because of the internals of Ajax, you won’t be able to open the index.html file in a browser. You need to run the code on a local server for it to work properly. If you’re on macOS you can run a simple HTTP server easily through Python, which is installed by default on macOS machines. Simply run the following through a terminal window within the directory of your project:

python -m SimpleHTTPServer

 

And then you can load http://localhost:8080 in a browser to view it. Another cross-platform way of setting up a local server is using Node.js. Node.js can be installed on all platforms. One way to get it is to go to Node.js. This will give you the runtime for your platform.

 

Once installed, Node.js includes a package manager. Node Package Manager (npm) allows you to download utilities built in JavaScript, which for purposes of this blog will let you use Node.js as a local server.

 

To make your current folder the root of your web server, you will have to use Terminal on macOS or a command-line utility on Windows (Git Bash, for example).

 

At the command line, navigate to the folder you want to serve and install the http-server module. Use the command npm install http-server –g. The –g flag means that this will be installed globally. You can set up any folder as a server once this is installed.

 

If you are not already at the folder you want to serve, make sure you navigate to it. Then launch the server by typing http-server. This will create a server that you can now open your browser and go to localhost:8080.

 

Once you’ve got that set up, view the site in your browser and open the developer tools.

You can see that jQuery turns the JSON into an object—so you don’t have to do the parsing stage. If you give the Ajax method the wrong URL, you’ll see an error thrown.

 

Now see what happens if you define the fail() method:

$(function() {
$.ajax({
"url": "/sample2.json",
"type": "get",
"dataType": "json"
}).fail(function(){
console.log(‘fail’, arguments);
});
});

 

You can output the details as they are passed back through the fail() function, but we’ve never really found any huge use for it.

Just like the fadeIn() and fadeOut() convenience-type methods that you saw with animations, there are some that exist for Ajax, too. You could use the getJSON() method (jQuery API Documentation. getJSON/) to trim the preceding example to the following:

 

$(function() {
$.getJSON("/sample.json", function(data) {
console.log(data);
});
});
This is equivalent to the following:
$.ajax({
"url": "/sample.json",
"dataType": "json"
}).done(function(){
});

 

So as you can see, it saves a little bit of work. You will notice that there’s no error message defined. This is because get JSON() only supports defining a function if the Ajax request succeeded.

 

You might decide this is acceptable, but it is best practice to deal with errors, so you might prefer, as we do, to stick to using $.ajax() directly, so you can define an error handler.

 

Thankfully, this all became easier post–jQuery 1.5 with Deferreds (jQuery API Documentation category/deferred-object/), which are ways to manage callbacks in a much nicer way. Deferreds are very powerful, but you’ll only need to scratch the surface for your Ajax work. 

 

Let’s take a moment to understand the jqXHR object. This is a wrapper around the browser’s native XMLHttpRequest object—the way Ajax requests are done with just JavaScript, making life much easier for you.

 

Every jQuery Ajax method—both the convenience ones like $.getJSON() and the main $.ajax() method—returns an instance of this object. What you can then do is add your callback methods onto this, meaning you don’t have to define them within the call to the Ajax method. For example, rather than:

$.ajax({
"url": "/someUrl",
"success": function() {
//before deferred objects
//do something here
}
});
you could do this:
var req = $.ajax({
"url": "/someUrl"
});
req.done(function() {
//do something
});

 

You save the returned value of $.ajax() (the jqXHR object) to a variable, and then you can declare callback functions on that, which is cleaner.

 

Take a look at the arguments that are passed into these functions, starting with done(response, status, jqXHR):

  • response is the response from the server; typically, the JSON the server has responded to.
  • status is a string denoting the status; with done(), it is nearly always "success".
  • jqXHR returns the jqXHR object.

 

With fail(), the order is slightly different; it is the same order as the arguments in the error callback you used earlier:

.fail(jqXHR, status, errorThrown)

always() is passed the same arguments as .done() or fail(), depending on which one runs (they can never both run).

The real advantage of this is that you can set up multiple callbacks:

var req = $.ajax({
"url": "/someUrl"
});
req.done(function() {
//do something
});
req.done(function() {
//do something else
});
req.always(function() {
//always do this
});

 

This means that if you have more than one thing to do when you get data back, you can split it up into multiple functions to keep things more organized. The .always() callback is really useful for executing something regardless of the success or failure of the Ajax request. From this point on in the blog, we’ll be using this callback style, and we encourage you to do the same.

 

A Real API TVmaze

TV

TVmaze (Your personal TV guide) is a web site for fans of all sorts of TV shows. This site also has a free and open API that returns results formatted as JSON objects. You can find the documentation at http://www. TVmaze - Add TV information to your website or app..

 

If, for example, you wanted to get information on a TV show or a movie, you can use the URL provided with shows?q=showName, where the placeholder showName is be the name of the show you are searching for.

 

This will return a JSON object with information such as ID, language, and summary. A search for the show “Gravity Falls” (http://api.tvmaze.com/search/shows?q=Gravity%20Falls) would return an object similar.

 

With this information, you can now make more specific requests. You can take the ID number and request all the episodes. The documentation uses :id as a placeholder. Making a call to http://api. http://tvmaze.com/shows/:id/episodes retrieves the episode list. The code would look like this:

$(function() {

var req = $.ajax({
url: " http://api.tvmaze.com/shows/396/episodes "
});
req.done(function(data) {
console.log(data);
});
});

 

Load the console to see what you get.

There may be instances when a call to a remote server returns an error. It may look something like this: “XMLHttpRequest cannot load http://api.mysite.com. Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin.”

 

Be aware that not all browsers will explain why the Ajax request failed, but will only inform you that it did. If you’re ever in doubt as to why a request failed, it’s a good idea to load it up in a browser that you know will show you the errors more explicitly, such as Chrome’s console.

 

This comes down to security. By default, the browser won’t allow one domain to make an Ajax call to a URL on another domain to pull in data, because this could be potentially dangerous. The Mozilla Developer Network (Cross-Origin Resource Sharing (CORS)) explains it nicely:

 

A resource makes a cross-origin HTTP request when it requests a resource from a different domain, protocol, or port to its own. For example, an HTML page served from Domain-a.com makes an <img> class='lazy' data-src request for http://domain-b.com/image.jpg. Many pages on the web today load resources like CSS stylesheets, images, and scripts from separate domains.

 

For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and Fetch follow the same-origin policy.

So, a web application using XMLHttpRequest or Fetch could only make HTTP requests to its own domain. To improve web applications, developers asked browser vendors to allow cross-domain requests.

 

Of course, this is not practical when it comes to using third-party APIs, and hence, many workarounds exist. One workaround is Cross-Origin Resource Sharing (CORS), which allows the server to include a header in its response, stating that a cross-origin request is valid.

 

Another solution, the one commonly used today, is to use JSONP, which stands for JSON Padded. A blog post from Johnny Wey (https://johnnywey.wordpress.com/2012/05/20/jsonp-how-does-it-work/) explains it in detail, but this bit from the blog particularly gets to the essence of how it works:

 

The idea of JSONP is actually pretty simple: toss a script tag into the DOM with a reference to a resource that returns JSON data. Have the server return said JSON with “padding” (the “P” part of JSONP) that executes a function wrapping the incoming data.

 

At this point, you may have realized something: you can’t make requests to servers to get at JSON, but you’re able to include external style sheets or scripts. For example, blog 1 showed you how to include the jQuery source from the Google CDN in a regular script tag:

<script class='lazy' data-src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

 

What if you could put the URL of the data you want into a script tag and get the server’s response as a JavaScript script, thus allowing you to get at the data? This is how JSONP works.

 

Providing that the server supports it (and most popular APIs will), you can use it. It works by wrapping the response from the server in a function. For example, the server might respond with

someFunction(data);

 

data is the JSON data. That is then included as regular JavaScript in your page, and then you can define someFunction to process the data. That is how JSONP works.

 

Thankfully, jQuery does all this for you to make it easier; so you don’t need to worry about such specifics when working with jQuery, but it’s good to know how things work.

 

So, how easy is it to get working in jQuery? Incredibly. Here is an example:

$(function() {

var req = $.ajax({
url: "REMOTE-SITE.COM"
});
req.done(function(data) {
console.log(data);
});
});
Add the dataType property to the ajax call:
$(function() {
var req = $.ajax({
url: "REMOTE-SITE.COM",
dataType: "jsonp"
});
req.done(function(data) {
console.log(data);
});
});

 

Before continuing, there is one major caveat to JSONP that’s worth mentioning, and that is that error callbacks will not run if something goes wrong. It is an unfortunate trade-off that you have to work around.

 

Writing a jQuery Plug-in

Writing a jQuery Plug-in

jQuery plug-ins are something that beginners tend to shy away from or are afraid to use. Plug-ins seem to be built up in people’s minds as incredibly complex things to use.

 

But once you learn how they work, you’ll find them actually very straightforward, and you’ll find yourself making multiple plug-ins while working. Plug-ins are not as complicated as you might think, as this blog will demonstrate.

 

After exploring the benefits of the plug-in and when to turn code into one, you will learn about different types of plug-ins, build a few small plug-ins to see how they work, and discover how to make them more configurable to a potential developer. 

 

Why a Plug-in

plug-in

There are typical patterns or signs you notice when writing code that are worthwhile to abstract into a plug-in. If you find yourself imagining another project or situation in which some code you’ve written could be reused, that’s a good sign that you should turn it into a plug-in. Your accordion code is a perfect example of this.

 

If you find yourself writing very similar code multiple times on different projects, it is a great sign that you should spend time producing a plug-in that can then be easily reused with little effort.

 

If you find yourself writing code to build a simple accordion more than once, it’s time to stop and build a plug-in. It might take a bit longer initially, but afterward you’ve got a nice, self-contained plug-in that you will never have to write again. Write once, benefit multiple times.

 

So far, we’ve spoken about plug-ins in the context of an accordion, but plug-ins can really be made for anything you find yourself doing a lot. It could be a small, three-line plug-in simply to make a certain action much easier, or it could be as large as a complicated image slider.

 

Your First jQuery Plug-in

Your first jQuery plug-in is going to be incredibly simple. It’s just going to log out the value of the ID attribute for every element it’s called on. Before writing a plug-in, it is useful to imagine how another developer will use your plug-in. In this case, imagine doing the following:

$("div").logId();

 

You should be able to open your browser console and see one log statement for every element that $("div") returned. The log should simply be the element’s ID attribute, or blank if the element does not have one.

 

The best way to see how to create this is to dive in and start writing code, with explanations as you go. So, create a new directory, perhaps called logid-plug-in or similar, and put some files in it. First, create index.html:

<!DOCTYPE html>

<html>
<head>
<title>blog 09, Exercise 01</title>
<script class='lazy' data-src=jquery.js></script>
<script class='lazy' data-src=logid.jquery.js></script>
<script class='lazy' data-src=app.js></script>
</head>
<body>
<div id=div1>Hello</div>
<div id=div2>Hello</div>
<div id=div3>Hello</div>
<div id=div4>Hello</div>
<div id=div5>Hello</div>
<div id=div6>Hello</div>
<div id=div7>Hello</div>
</body>
</html>

 

Put the jQuery source in the directory, too, in a file named jquery.js. Finally, create two more blank files. The first should be called logid.jquery.js, which will house your plug-in, and the second app.js, where you’ll write the code that utilizes the plug-in. It’s convention to name your plug-in file name.jquery. js, so you’ll stick to that.

 

We’ll show you the implementation of the plug-in, and then explain it in detail. Here’s the entirety of the code to get your logId plug-in, which you should put into logid.jquery.js:

$.fn.logId = function() {
return this.each(function() {
console.log(http://this.id);
});
};
And here’s what you should put into app.js to test it out:
$(function() {
$("div").logId();
});

 

Take a step back to figure out exactly what happened here. The first line adds your method, logId, to jQuery. This is also referred to as extending jQuery:

$.fn.logId = function() {...});

 

Adding a method to the $.fn method means it’s available to be used on a jQuery object. Remember, a jQuery object is the result of running $("div") or similar. All this line does is add a new property to $.fn, logId, which is equal to a function.

The next piece of interest is the each() method:

return this.each(function() {...});

 

Within the function, the value of this is the jQuery object your function was called on. So when you call $("div").logId(), the value of this refers to the jQuery object containing the result of $("div"), which will contain all the divs on the page. Therefore, you want to loop over every element within this, so you can run your code on every element.

 

The other important thing to note is the fact that you return the result of the loop. When looping over something, the initial “thing” will always be returned. So when you run:

return this.each(function() {...});

 

At the end of it, this is returned. This means your plug-in is chainable, or that someone could call another method after yours, such as:

$("div").logId().fadeOut();

 

Unless your plug-in is specifically designed to return a particular value, it should always be chainable. People will assume your plug-in is chainable—and they will get mighty confused if it’s not. There’s really no excuse not to make it chainable.

 

Finally, within the loop, the value of this refers to the individual DOM element you are looping over. Note that this is not a jQuery object, but just the DOM element. If you wanted to call jQuery methods on it, you’d have to run $(this) first.

 

All you need to do within the loop is get the element’s ID. You could do the following:

$(this).attr("id");

But in actual fact, it’s easy to get at the ID of a DOM element without needing jQuery:

http://this.id

 

That achieves the same thing and is leaner than the jQuery equivalent, so there’s no reason not to.

So, you now have the following:

$.fn.logId = function() {

return this.each(function() {

console.log(http://this.id);

});

};

 

Congratulations! You’ve just written your first jQuery plug-in!

Improvements

 

There are still a few issues with this plug-in, though. The first to tackle is the problem with how you define your plug-in. Currently it’s done like so:

$.fn.logId = function() {...});

 

However, there is no guarantee that the $ variable refers to jQuery. Sometimes people who use jQuery will not allow it to use the $ variable because another script or plug-in might be using it.

 

Granted, this is fairly unlikely, but you should never assume that $ is jQuery. It’s easy enough to get jQuery to release $, through its noConflict() method (jQuery API Documentation). Here’s an example:

 
jQuery.noConflict();
// now, $ is reset to whatever it was before jQuery was loaded jQuery("div");
jQuery exists as two global variables by default: $ and jQuery. They both are identical, so if jQuery.
noConflict() is called, you can still use jQuery through the jQuery method, but not through $.
To be safe, you should use the jQuery variable rather than $ within your plug-in:
jQuery.fn.logId = function() {
return this.each(function() {
console.log(http://this.id);
});
};

 

But typing jQuery instead of $ is irritating. Thankfully, there’s a better way to do things.

One way to do it would be to create a function that defines your function. The very first thing you do is set $ equal to jQuery:

 

var definePlugin = function() {

var $ = jQuery;
$.fn.logId = function() {
return this.each(function() {
console.log(http://this.id);
});
};
};
definePlugin();

 

This works because variables defined within a function are only available within that function, so you can safely define $ without defining it globally. You may not like this solution though, even though it works. Defining and then calling a function seems like a long-winded way of doing things. If only there was a way of defining and then immediately executing a function…

 

Immediately-Invoked Function Expressions

code

The term “Immediately-Invoked Function Expression” (IIFE) was coined by prolific JavaScript developer Ben Alman on his personal blog, in an article about functions that are defined and then immediately invoked (Immediately-Invoked Function Expression (IIFE)).

 

The article is a great read but goes into a lot of depth, so you may want to read it once you’re more comfortable with jQuery and wish to learn more about the specifics of JavaScript.

 

An IIFE is a function that is immediately defined and then executed. Try loading your JS console in a browser and then running this line of code:

(function() { console.log("hey"); })();

 

What you will see is the word “hey” logged right back at you. You just defined a function—albeit an anonymous one (you never gave it a name)—and executed it, all in the same line. The key here, as you might have guessed, is the pair of parentheses at the end of the line and the pair around the function definition.

 

The brackets around the function are due to how JavaScript’s parser works. If you try:

function() { console.log("hey"); }

you will get a syntax error:

SyntaxError: Unexpected token (

 

This is the syntax error Google Chrome provides; each browser does it slightly different. Firefox, for example, will state “SyntaxError: function statement requires a name.”

 

This is because the parser thinks you’re defining a new function, and as such is expecting a name between the function keyword and the opening bracket. It thinks you are declaring a function. Hence, this doesn’t work because you’ll get the same error: function() { console.log("hey"); }()

 

Wrapping it in parentheses tells the parser that it’s an expression rather than a declaration, meaning that it doesn’t expect a name and parses the line as a function expression; in other words, it evaluates the contents of the function. The second, empty pair of parentheses simply calls your newly defined function.

 

So what does this all have to do with the initial problem? Well, IIFEs can take parameters, too. Try this in your console:

(function(x) { console.log(x); })("hey");

Here you define a function that takes one argument, x, and logs it. When you call it, you then pass in that value. It’s no different than doing this:

function log(x) {

console.log(x);

};

log("hey");

 

Now that you know you can do that, you should be able to see how it applies to the initial issue. You can define the function, immediately execute it, and pass in jQuery much more succinctly:

(function($) {

// our plugin here })(jQuery);
Within that function, you can use $ as jQuery, regardless of whether it is defined as jQuery outside the function . With that, your plug-in becomes much more robust:
(function($) {
$.fn.logId = function() {
return this.each(function() {
console.log(http://this.id);
});
};
})(jQuery);

 

Giving the User Options

user

When making a plug-in, it might be beneficial to let the user choose how it acts in a certain spot. You might let the user choose the text color or, if your plug-in animates DOM elements, how quickly to animate something.

 

You are now going to create another small plug-in similar to your first. It will be a function for logging to the console, but for logging any attribute. So you’ll need to let the user pass in the attribute they want to be logged. 

 

Create a new directory, perhaps logattribute-plug-in, and create a new index.html file with the following code. It is identical to the HTML in the previous plug-in you made, except the file name of your plug-in is different.

 

<!DOCTYPE html>

<html>
<head>
<title>blog 09, Exercise 02</title>
<script class='lazy' data-src=jquery.js></script>
<script class='lazy' data-src=logattr.jquery.js></script>
<script class='lazy' data-src=app.js></script>
</head>
<body>
<div id=div1>Hello</div>
<div id=div2>Hello</div>
<div id=div3>Hello</div>
<div id=div4>Hello</div>
<div id=div5>Hello</div>
<div id=div6>Hello</div>
<div id=div7>Hello</div>
</body>
</html>
Create a blank app.js file and a logattr.jquery.js file, which should contain the following code, the basis for your plug-in:
(function($) {
$.fn.logAttr = function() {
};
})(jQuery);

 

You’re using an IIFE once more around your plug-in code, which is something you’ll do for all plug-ins from now on.

Take a first stab at implementing the following:

(function($) {
$.fn.logAttr = function(attr) {
return this.each(function() {
console.log($(this).attr(attr));
});
};
})(jQuery);

 

You simply define a function that takes an attribute as an argument, and then use the attr() method within the loop to log it out. To test it out, place this code into app.js and then load index.html in the browser:

$(function() {

$("div").logAttr("id");

});

 

If you check out the console, you’ll see each div’s ID logged.

Let’s say you’re building this for a client, who comes back with the following requests:

  • They would like to be able to define a backup value to log if the element doesn’t have the attribute specified.
  • They would like to be able to switch between using the console and simply alerting variables, because some browsers they need to test in do not have a console.

 

These are both reasonable requests. Sort out the backup value first. It would make sense for it to be another parameter, so add it. Then, you can log out the attribute if it exists, and if not, the backup value. Let’s use the following:

(function($) {
$.fn.logAttr = function(attr, backup) {
return this.each(function() {
console.log($(this).attr(attr) || backup);
});
};
})(jQuery);
This is the key line:
console.log($(this).attr(attr) || backup);

 

It works because if the element doesn’t have the attribute, undefined is returned. Then, the statement becomes

undefined || backup

undefined is evaluated to false, so then backup is evaluated and returned.

To test this, add a rel attribute to one of the divs:

<div id="div1" rel="someDiv">Hello</div>
And then change the contents of app.js to
$(function() {
$("div").logAttr("rel", "N/A");
});

 

When you run that in the browser, you’ll see "someDiv" logged once, and "N/A" logged six times.

Next, add another option to the plug-in, which if set to true, will use alert instead of console.log:

 

(function($) {
$.fn.logAttr = function(attr, backup, useAlert) { return this.each(function() {
if(useAlert) {
alert($(this).attr(attr) || backup);
} else { console.log($(this).attr(attr) || backup);
}
});
};
})(jQuery);
And it’s used by simply adding true as the third argument when you call the plug-in:
$(function() {
$("div").logAttr("rel", "N/A", true);
});

 

This is starting to get messy, however. A better option would be to let the end user pass in an object of key-value pairs that are the options you want. You’ll do that shortly. First, there’s a bit of refactoring you can do:

 

if(useAlert) {

alert($(this).attr(attr) || backup);
} else { console.log($(this).attr(attr) || backup);
}
Here you are repeating $(this).attr(attr) || backup twice. Better to save that to a variable:
var val = $(this).attr(attr) || backup;
if(useAlert) {
alert(val);
} else { console.log(val);
}
However, this can be further shortened with the ternary operator:
var val = $(this).attr(attr) || backup;
useAlert ? alert(val) : console.log(val);

 

That’s a much nicer implementation.

 

Adding Options to Your Plug-ins

We don’t like the way that the user configures the plug-in. In our opinion, the following is messy:

$.fn.logAttr = function(attr, backup, useAlert)

If users want to set useAlert to true, but leave the backup as its default (which is undefined), they’d have to call the plug-in like this:

$("div").logAttr("rel", undefined, true);

 

And that is incredibly messy. You should only make users specify options when they don’t want to use the default values. That’s where using an object to store the options is beneficial. So instead, you can have users call the plug-in like so:

$("div").logAttr({

attr: "rel",

useAlert: true

});

This is the next thing you’ll do in this blog, before finishing your logAttr plug-in and looking at the accordion plug-in using the code that you wrote earlier.

 

In terms of implementing the ability to pass in an object , there are three steps:

  • Create an object containing the options, set to the default values.
  • Allow the user to pass in an object containing the desired settings.
  • Overwrite your defaults with the user’s options.

The first two steps are very easy. First, change the function so that it takes one argument, the options object:

$.fn.logAttr = function(opts) {

And then, within that function, define the defaults:

var defaults = {

attr: "id",

backup: "N/A",

useAlert: false

};

The next part is to take the defaults and overwrite them with the options the user passed in. This is such a common thing for plug-ins to do that jQuery provides a utility method called $.extend (http://api. http://jquery.com/jQuery.extend/) to do it.

 

It has a few use cases, but the main one for your use is that it can take two objects and merge them into one object. If a property is defined in both objects, the later object takes precedence. Take these two objects, for example:

 

var objectOne = { x: 2, y: 3, z: 4 };

var objectTwo = { x: 4, a: 5 };

Then call $.extend, passing in these objects:

$.extend(objectOne, objectTwo);

 

This will take objectTwo and merge it into objectOne, modifying it to contain the results of merging the objects. In this case, objectOne would look like this: { x: 4, y: 3, z: 4, a: 5 }

 

Notice that because x existed in object Two, it was used over the x that existed within objectOne. Typically, you will not want to modify either of the objects, but instead create a new object from the result of merging.

This can be achieved by passing in a blank object to $.extend as the first argument. The return value of $.extend is always the merged object.

 

var objectOne = { x: 2, y: 3, z: 4 };

var objectTwo = { x: 4, a: 5 };
var merged = $.extend({}, objectOne, objectTwo);
This leaves you a new object, merged, that contains:
{ x: 4, y: 3, z: 4, a: 5 }
However, objectOne and objectTwo have not been altered. It’s this usage that you use in your plug-ins.
Implementing this into your plug-in, you end up with the following:
(function($) {
$.fn.logAttr = function(opts) {
var defaults = {
attr: "id",
backup: "N/A",
useAlert: false
};
var options = $.extend({}, defaults, opts);
return this.each(function() {
var val = $(this).attr(options.attr) || options.backup; options.useAlert ? alert(val) : console.log(val);
});
};
})(jQuery);

 

After defining the defaults, you then use $.extend to merge opts, the object the user passed in, into defaults, and create a new object. $.extend returns this value, so you store it to options, a new variable.

 

Previously in your options, you referred to the user options as attr or backup; now they exist within options, so they have to be referred to as options.attr and options.backup.

Now the usage of your plug-in has changed, so head into app.js and update it:

$(function() {


$("div").logAttr({

attr: "rel"

});

});

 

The beauty of using an option should now be apparent. It’s so much clearer as to which options you’re setting because you set them through a key/value pairs object. Also, you only have to specify the ones that you want different from the default.

Now that you’ve made a slightly more complicated function, it’s time to revisit the code for the accordion you wrote back in blog 5 and turn that into a plug-in.

 

The Accordion Plug-in

Let’s revisit the code you wrote for your accordion. You could either create a new directory or copy the previous one. Here are the contents of app.js:

 

$(function() {
var accordion = $("#accordion");
var headings = $("h2");
var paragraphs = $("p");
var animateAccordion = function(elem, duration, easing) { paragraphs.stop(true, true).slideUp(duration, easing); $(elem).stop(true, true).slideDown(duration, easing);
}
paragraphs.not(":first").hide();
accordion.on("click", "h2", function() {
var t = $(this);
var tPara = t.next();
if(!http://tPara.is(":visible")) {
tPara.trigger("showParagraph");
}
});
accordion.on("showParagraph", "p", function() { animateAccordion(this, 600, "easeInCirc");
});
});
And here’s the HTML from index.html:
<!DOCTYPE html>
<html>
<head>
<title>blog 09, Accordion Plugin</title>
<script class='lazy' data-src=jquery.js></script>
<script class='lazy' data-src=app.js></script>
<link rel=stylesheet type=text/css href=style.css />
</head>
<body>
<div id=accordion>
<h2>Heading</h2>
<p>Thesis Scientist 2.</p>
<h2>Heading 2</h2>
<p> Thesis Scientist 3.</p>
<h2>Heading 3</h2>
<p>Thesis Scientist 4.</p>
</div>
</body>
</html>
You also had a small amount of CSS in style.css:
#accordion {
width: 500px;
border: 1px solid black;
}
#accordion h2 {
padding: 5px;
margin: 0;
background: #ddd;
}
#accordion p {
padding: 0 5px;
}

 

In the original accordion, you also included the jQuery UI source, so you could use different easing types. You’re not going to include that this time; just simply use the default animation. Start work on turning it into a plug-in.

 

A likely use for the plug-in is to call it on the div that contains all the content. You then have to pass it the element types that are used for the headings and content. For example, you might call it like so:

$("#accordion").accordion({
headings: "h2",
content: "p"
});
Create a new file, accordion.jquery.js, and leave it blank. If you like, you might load up your old accordion code to use as a reference. Alter app.js so that it uses your plug-in:
$(function() {
$("#accordion").accordion({
headings: "h2",
content: "p"
});
});

 

Obviously, this won’t work right now, but your task now is to get it working. You should also edit index.

html, adding in the new accordion.jquery.js file before app.js:
<script class='lazy' data-src="jquery.js"></script>
<script class='lazy' data-src="accordion.jquery.js"></script>
<script class='lazy' data-src="app.js"></script>
Now you can get started. At the top of the plug-in file (accordion.jquery.js), write the initial template:
(function($) {
$.fn.accordion = function(opts) {
var defaults = {
headings: "h2",
content: "p"
};
var options = $.extend({}, defaults, opts);
};
})(jQuery);

 

Here you use an IIFE to make certain that you can use $ and that it refers to jQuery. Create the function, which will take one argument—an object of options—before setting up the default options. You may need more options; if you do, you can add them as you go. Then, create the final set of objects, merging the user’s options with the defaults.

 

Next, you set up the loop that will contain your functionality. This loops over every element the plug-in was called on. Remember, you return it so that your plug-in is chainable.

 

Within the loop, you can get at the current element through this, and so create a $this variable, which refers to $(this), which is the current element wrapped in the jQuery object.

 

If you're working on a project with lots of variables, some of which refer to jQuery objects and others that don’t, consider prefixing the ones that do with a $ as a visual note to yourself that those variables are jQuery objects.

return this.each(function() {
var $this = $(this);
});
You then need to store references to the headings and content. In your initial accordion, you did the following:
var headings = $("h2");
var paragraphs = $("p");
But in this case, the selectors are defined within the options. You should also limit your search to within the accordion:
return this.each(function() {
var $this = $(this);
var headings = $this.children(options.headings); var paragraphs = $this.children(options.content);
});
If you look at the initial accordion, you had a small utility function, animateAccordion(), which did the animations for you:
var animateAccordion = function(elem, duration, easing) { paragraphs.stop(true, true).slideUp(duration, easing); $(elem).stop(true, true).slideDown(duration, easing);
}

 

You’re going to keep this function, but with one difference. Because you are no longer allowing the easing to be customized, and are sticking with the default, remove that option. Your plug-in loop should now look like this:

return this.each(function() {
var $this = $(this);
var headings = $this.children(options.headings); var paragraphs = $this.children(options.content);
var animateAccordion = function(elem, duration) { paragraphs.stop(true, true).slideUp(duration); $(elem).stop(true, true).slideDown(duration);
};
});
Your next piece of code does the animations. It needs very little changing. This is it for now:
paragraphs.not(":first").hide();
accordion.on("click", "h2", function() {
var t = $(this);
var tPara = t.next();
if(!http://tPara.is(":visible")) {
tPara.trigger("showParagraph");
}
});
accordion.on("showParagraph", "p", function() { animateAccordion(this, 600, "easeInCirc");
});

 

There are only a couple of pieces to change. First, instead of referring to the variable accordion, you now refer to $this. Second, both of the calls refer to the headings and contents through "h2" or "p".

 

You need to use the options.headings and options.content variables instead. Finally, remove the third parameter from the animateAccordion() argument because you are no longer supporting different easing methods.

 

That leaves the code looking like so:

paragraphs.not(":first").hide();
$this.on("click", options.headings, function() { var t = $(this);
var tPara = t.next();
if(!http://tPara.is(":visible")) {
tPara.trigger("showParagraph");
}
});
$this.on("showParagraph", options.content, function() { animateAccordion(this, 600);
});
And you are now done. Put that within the loop in your plug-in, and your accordion is complete!
accordion.jquery.js should now look like this:
(function($) {
$.fn.accordion = function(opts) {
var defaults = {
headings: "h2",
content: "p"
};
var options = $.extend({}, defaults, opts);
return this.each(function() {
var $this = $(this);
var headings = $this.children(options.headings); var paragraphs = $this.children(options.content);
var animateAccordion = function(elem, duration) { paragraphs.stop(true, true).slideUp(duration); $(elem).stop(true, true).slideDown(duration);
};
paragraphs.not(":first").hide();
$this.on("click", options.headings, function() { var t = $(this);
var tPara = t.next();
if(!http://tPara.is(":visible")) {
tPara.trigger("showParagraph");
}
});
$this.on("showParagraph", options.content, function() { animateAccordion(this, 600);
});
});
};
})(jQuery);

 

If you load index.html in a browser, you should see it all working as before. Congratulations on your first “proper” jQuery plug-in! You could make some improvements, though. The first is providing support for callbacks.

 

Adding Callback Support

Support

It would be fantastic if you could allow anyone using your plug-in to define a callback that would be run once an animation happened, which meant that the user switched to a new section.

 

You might think adding callback functionality is complicated, but it’s really not. The first thing to do is add a new option to your defaults, defining what the default callback function should be.

 

If the user doesn’t define one, then presumably she doesn’t want anything to run once the animation is done, so the default should simply be a function that does nothing:

var defaults = {

headings: "h2",

content: "p",

callback: function() {}

};

 

Next, you need to edit your animateAccordion() function to take a callback. It should take it as an argument and pass it straight through to the animations. However, you should only pass it through to one of them.

 

If you were to pass it through to both the slideUp() and slideDown() functions, you would have it called twice. Both animations run for the same amount of time, so they both finish at the same time. This means you can add it to only one of the animations:

var animateAccordion = function(elem, duration, callback) {
paragraphs.stop(true, true).slideUp(duration);
$(elem).stop(true, true).slideDown(duration, callback);
};
Finally, you need to edit the call to animateAccordion() to pass through the callback:
$this.on("showParagraph", options.content, function() { animateAccordion(this, 600, options.callback);
});

 

Note that options.callback is simply a reference to the function. options.callback() would execute the function, which is not what you want. Referring to a function without parentheses means you get a reference to the function and it does not execute. Let’s test this out. Edit your app.js file so that you pass in a callback:

$(function() {
$("#accordion").accordion({
headings: "h2",
content: "p",
callback: function() {
alert("changed");
}
});
});

 

Now, whenever anything slides down within the accordion, you’ll get an alert.

The final tweak you’ll make is to allow the user to set the duration. For any plug-ins that include animations, it’s important to let the user change the speed. This is very easy to do. Add the default:

var defaults = {

headings: "h2",
content: "p",
callback: function() {},
duration: 600
};
And again, it’s just a case of editing the call to animateAccordion():
$this.on("showParagraph", options.content, function() { animateAccordion(this, options.duration, options.callback);
});
And with that, your accordion plug-in is done. Here’s the final code:
(function($) {
$.fn.accordion = function(opts) {
var defaults = {
headings: "h2",
content: "p",
callback: function() {},
duration: 600
};
var options = $.extend({}, defaults, opts);
return this.each(function() {
var $this = $(this);
var headings = $this.children(options.headings); var paragraphs = $this.children(options.content);
var animateAccordion = function(elem, duration, callback) {
paragraphs.stop(true, true).slideUp(duration);
$(elem).stop(true, true).slideDown(duration, callback);
};
paragraphs.not(":first").hide();
$this.on("click", options.headings, function() { var t = $(this);
var tPara = t.next();
if(!http://tPara.is(":visible")) {
tPara.trigger("showParagraph");
}
});
$this.on("showParagraph", options.content, function() { animateAccordion(this, options.duration, options.callback);
});
});
};
})(jQuery);
You can then use this option to set the animation, like so:
$(function() {
$("#accordion").accordion({
duration: 10000
});
});

 

More jQuery Plug-ins

More jQuery Plug-ins

You ended the last blog with a pretty awesome accordion plug-in that you built based on the initial accordion code you wrote in blog 5. In this blog, you will take your TVmaze API work from blog 8 and turn it into a plug-in. You’ll do this by making a slightly different type of plug-in, one that exists directly on the jQuery object. This means instead of calling it on a set, as you did previously:

$("div").somePlugin();

you call it directly:

$.somePlugin();

There are certain situations in which you should use the first style, and other situations where you should use the latter. This blog explains the latter. There are a few other things to cover in this blog:

 

You’ll further explore ways to make your plug-in more useful. Keeping it generic and making sure it does the job it is supposed to do makes it easier for others to use. You’ll look at techniques for doing this. We’ll briefly discuss best practices for documenting your plug-in and show examples.

 

The TVmaze API Plug-in

To refresh your memory, here’s the code you wrote for grabbing the list of episodes for a show including the use of the dataType property that we used in blog:

$(function() {

var req = $.ajax({

url: " http://api.tvmaze.com/shows/396/episodes ",

dataType: "jsonp"

});

req.done(function(data) {

console.log(data);

});

 

It’s time to turn this code into a jQuery plug-in. It is going to exist directly on the jQuery object because you’re going to extend your plug-in to have two distinct methods. One will get the data for a single show, and the other will get all the episodes from the show and construct a list of them. The goal is to be able to call them like so:

$.tvmaze.getShow();

$.tvmaze.getEpisodes();

 

So your plug-in will exist on the jQuery object, but contain more than one method to be called. First, create a new directory for this project. If you remember using npm before, here is a good opportunity to use it again. If you have not installed http-server, make sure Node.js has already been installed, then at the command line type npm install –g http-server. After that, also using the command line, type http-server. This will make your current directory a local web server.

 

You can see everything that you are working on in your browser by typing localhost:8080. First you will create the basic structure of the page. To make it look nice, you will also include Twitter Bootstrap. Create blank app.js and tvmaze.jquery.js files, and an index.html here we add the parts that we need to style the page using Bootstrap.

<!DOCTYPE html>

<html>
<head>
<title>blog 10, TVMaze Plugin</title>
<link rel=stylesheet href='add URL to bootstrap css'> </head>
<body>
<div class=container>
<h1> TV Maze – TV Show Search </h1>
<form>
<div class=form-group>
<input type=text class=form-control id=showInput placeholder="Search TV Show" required>
<button tyhpe=submit class="btn btn-primary" id-"submitButton">Submit</button> </dir>
</form>
</div>
<div>
<table class=table>
<thead id=tableHead>
<tr>
<td>Name</td>
<td>Network</td>
<td>Type</td>
<td>Image</td>
</tr>
</thead>
<tbody id=tableBody>
</tbody>
</table>
<table class=table>
<thead>
<tr>
<td>Airdate</td>
<td>Episode Name</td>
<td>Episode Number</td>
<td>Season</td>
<td>Run Time</td>
<td>Summary</td>
</tr>
</thead>
<tbody id=episodeInfo>
</tbody>
</table>
</div>
</div>
<script class='lazy' data-src=jquery.js></script>
<script class='lazy' data-src=tvmaze.jquery.js></script>
<script class='lazy' data-src=app.js></script>
</body>
</html>
At this point your page should look something like Figure 10-1.
Open tvmaze.jquery.js and add the following. We add the following to create the tvmaze object and assign methods to it:
(function($) {
$.tvmaze = {
getEpisode: function(showId, callback) {
var req = $.ajax({
url:'http://api.tvmaze.com/shows/' + showId + '/episodes'
});
req.done(callBack);
},
getShow: function(showName, callBack) {
var req = $.ajax({
url:'http://api.tvmaze.com/search/shows/?q=' + showName
});
req.done(callBack);
}
};
})(jQuery);

 

With the plug-in now in place, you can start to make calls to TVmaze. Over time, you can add features to make other API calls. For now, you can open app.js and start to get the application to work. Similar to the TVmaze plug-in, this is going to be an IIFE (Immediately-Invoked Function Expression). In short, it will run as soon as it has been created.

(function() {

$('#submitButton').on ('click', getShowName);
function getShowName(evt){
evt.proventDefault();
if($('#showInput')[0].valuie.length > 0){
let searchValue = $('#showInput')[0].value; $().tvmaze.getShow(searchValue, (results) => {
displayShowResults(results[0].show);
});
}
}
})();

 

At this point, the function would have executed and jQuery would add an event listener to "submitButton". When clicked, the function "getShowName()" is called and evaluates whether the value of the text field is greater than 0. If it is, it assigns the value to a variable called searchValue.

 

Here is where you get to use your recently created plug-in. The method getShow() is called with the value passed from the text field. In this example, you may notice that the callback function looks a little different. This example is using an arrow function. For your purposes, it works exactly the same as a normal anonymous function. Your result returns an array of objects that then get passed off to the displayShowResults() function, which you add next as follows:

 

Note For more information on how arrow functions are different than function expressions, look at the MDN Web Docs: Functions

Arrow_functions

function displayShowResults(results){
$('#tableBody').html('<td id="episodeName" data-episodeid="' + http://results.id + '">'
+ http://result.name + '</td>' + '<td>'
+ checkNetwork(results.network) + '</td>'
+ '<td>' + results.type + '</td>'
+ '<td> <img class="image-border" class='lazy' data-src=" '

+ results.image.medium '"> </td>');
$('#episodeInfo tr').remove();
$('#episodeName').on('click', (event) => { getEpisodes(event.target.dataset.episodeid);
});
}
function checkNetwork(networkName)
if(networkName != null) {
return http://networkName.name;
}else{
return 'Not Listed';
}
}

 

Here you start to display the results of the API call your plug-in made for you. jQuery adds a row with the results, displaying the ID, name, and image. There is also a function called checkNetwork(), which is included only in the case of the result returning from the API is null. In that instance, you would get an error. To avoid that, you can check if there is a null value and, if there is, just return the string 'Not Listed'.

 

The next line removes any previous listing of TV episodes. The first time it runs, there will be nothing to remove, but you will see shortly how this becomes important. Another click event is added to the ID episodeName.

 

If you were wondering what the data attribute is doing, here is where it comes in. The data attribute is part of HTML5 and allows you to add extra information that does not have any visual representation. When retrieving the information, you can look at the dataset property and call your custom-made property episodeid. With this intact, you can now make another call to the TVmaze plug-in and get all the episodes for that TV show:

function getEpisodes(episodeID){
$().tvmaze.getEpisodes(episodeID, function(results){
for(var I = 0; I < results.length; i++){
$('#episodeInfo').append('<tr> <td>’
+ results[i].airdate + '</td> <td>'
+ results[i].name + '</td> <td>'
+ results[i].number + '</td> <td>'
+ results[i].season + '</td> <td>'
+ results[i].runtime + '</td> <td>'
+ results[i].summary + '<td>'
+ '</tr>')
}
});
}

 

The last function in this example calls the TVmaze plug-in. When the results are returned, it will loop over them and append a new row to the existing table with information about the episodes.

If you are running this on your local web server (for example, http-server), you should be able to make calls to the API and get results back.

 

Documentation

We’d like to very briefly discuss how to document your plug-in. Documenting your plug-in is important for other developers who might use it, but for you as well. When you revisit a plug-in after an extended time, good documentation is really helpful.

You need to document each method clearly. It is a good idea to provide the following details:

  • Give a one- or two-sentence description of what the method does.
  • Note the options that the method takes in, example values, and the default value for every option that has one.
  • Give an example of the plug-in’s usage and the data it returns.

The following is an example of how I would document your getShow() method:

 

THE GETSHOW METHOD

getShow() is a method that takes in a string representing the name of a TV show and makes an Ajax request to TVmaze, returning the JSON data of that show.

•\ showName: This is a string that is the ID of the TV show you’d like to get the data for; for

example: “Gravity Falls”

•\ callback: A function that will be called when the Ajax request returns the data.

It takes a single string:

 

Here’s an example usage, and the response that’s received:

$.tvmaze.getShow({

showName:"Star Wars: Rebels",
callback: function(data) {
console.log(data);
}
});

 

And the JSON that is returned:

That’s an example of how I’d document a method. My key rule is that if I’m considering whether or not to document a certain bit of functionality, I do it anyway. It’s better to have too much documentation than not enough.

 

Recommend