Extend the jQuery library with your own reusable code
jQuery is a powerful library that delivers all of the core functions you need when developing a JavaScript project. However, sometimes it’s necessary to extend the core functions with custom code that helps you be more productive. In this article, learn how to create a custom reusable plug-in using the jQuery library.
Introduction
The jQuery library is designed to speed up JavaScript development. It helps you write less code by simplifying the way you write JavaScript. When using the jQuery library, you might find that you rewrite the same code for common functions. If this is the case, this may be a reason for you to write your own custom jQuery plug-in.
jQuery plug-ins let you extend the jQuery library with custom code; you can use plug-ins for any repetitive function. For example, many plug-ins are available for slideshows and for drop-down and accordion menus. If you search for jQuery plug-ins, you’ll find plenty of examples that you can use in your own projects (and see how they were built).
In this article, learn how to quickly create a custom jQuery plug-in. Example code and step-by-step instructions show you how to create a jQuery accordion plug-in. If you know jQuery and are ready to take your skills to the next level, this article is perfect for you.
You can download the source code for the examples used in this article.
Prerequisites
This article assumes you have a basic understanding of JavaScript, jQuery, and cascading style sheets. See Resources to learn more about these prerequisites.
Getting started
jQuery is a library that extends the JavaScript language. When creating a jQuery plug-in, you’re essentially extending the jQuery library, which in turn is extending JavaScript itself. Truly understanding how your plug-in extends the jQuery library requires an understanding of the JavaScript prototype
property. Although it is not used directly, the JavaScript prototype
property is used behind the scenes through the jQuery property fn
, which is a jQuery alias for the native JavaScript prototype
property.
To create a new jQuery plug-in using the fn
property, simply assign a plug-in name to the fn
property and point it to a new function that will act as the constructor function, similar to plain JavaScript. The code in Listing 1 shows how to define a new jQuery plug-in named accordion
by using the jQuery
object and the fn
property and assigning it to a new constructor function.
jQuery.fn.accordion = function() { // Add plugin code here };
Listing 1 shows one way to create a jQuery plug-in; there is nothing functionally wrong with the example. However, the recommended way to create a jQuery plug-in is to first create a wrapper function that lets you use the dollar sign ($
). By default, the dollar sign can cause conflicts with other JavaScript frameworks. If you wrap your plug-in in a function, conflicts won’t occur with other JavaScript frameworks and the use of the dollar sign. The example code in Listing 2 shows how to apply a wrapper function to a jQuery plug-in definition.
(function($) { $.fn.accordion = function() { // Add plugin code here }; })(jQuery);
In Listing 2 the jQuery
keyword is applied to the wrapper function, which lets you use the dollar sign within the plug-in as you do when using the fn
property. With the wrapper function in place, you can use the dollar sign in lieu of the jQuery
keyword anywhere throughout the plug-in without interfering with other third-party plug-ins. This option provides a way to write less code throughout the plug-in and helps to keep your plug-in code cleaner and easier to maintain.
Maintaining chainability
A benefit of jQuery is that it lets you use any type of selector. However, you must keep in mind that your plug-in can be dealing with several different element types. Using the this
keyword lets your plug-in apply the associated functions by accessing each element in a loop regardless of the element type. If you use the return
keyword in front of the each
loop, you can maintain chainability with your plug-in. Listing 3 shows the each
loop being assigned to a function handler and combined with the return
keyword.
(function($) { $.fn.accordion = function() { return this.each(function() { // Using return allows for chainability }); }; })(jQuery);
With the code in Listing 3, the example accordion plug-in can be used in a chain of method calls. With chainability—another great jQuery feature—your plug-in can be used in a chain of method calls. For example, the following code shows how an HTML element is faded out and then removed from the document object model (DOM) in a single chain of method calls.
$("#my-div").fadeOut().remove();
Structuring an accordion
A typical accordion design includes title bars and related content areas. Definition lists are a great HTML structure for accordions; dt
elements are used for titles and dd
elements are used for content areas. The HTML structure in Listing 4 is a definition list with four titles and their corresponding content areas.
<dl class="accordion" id="my-accordion"> <dt>Section 1</dt> <dd>Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam.</dd> <dt>Section 2</dt> <dd>Vestibulum a velit eu ante scelerisque vulputate.</dd> <dt>Section 3</dt> <dd>Nam mi. Proin viverra leo ut odio. Curabitur malesuada.</dd> <dt>Section 4</dt> <dd>Vivamus nisi metus, molestie vel, gravida in, condimentum sit amet, nunc.</dd> </dl>
The definition list in Listing 4 also has a CSS class named accordion
assigned to it. Without any CSS applied, this accordion structure looks similar to the bare-bones design in Figure 1.
The accordion
class is used to apply styles to the overall definition list, the titles, and the content areas. In the example in Listing 5, the accordion
class itself applies a width, border, font family, and font size. You can modify any of the proceeding CSS examples to include your own custom styles, such as color, font family, sizes, and spacing.
.accordion { width: 500px; border: 1px solid #ccc; border-bottom: none; font-family: Arial, Helvetica, sans-serif; font-size: 12px; }
You then use the accordion
CSS class to define the styles for the titles (dt
) and content (dd
). The titles and content both include shared styles that define a bottom border and set the margin to 0, which allows the title bars and content areas to rest snuggly against each other, as in Listing 6.
.accordion dt, .accordion dd { border-bottom: 1px solid #ccc; margin: 0px; }
To make the dt
element look more like a title bar, set a background color and add a pointer cursor so it’s apparent to users that the title bar is clickable. Various other styles are included in these classes, such as padding, a font size, and a font weight. The dd
element has added padding to space out the description a bit from the titles. Listing 7 shows an example.
.accordion dt { background: #eaeaea; cursor: pointer; padding: 8px 4px; font-size: 13px; font-weight: bold; } .accordion dd { padding: 12px 8px; }
With all of the CSS added, the visual result is more complete and accordion-like, as in Figure 2.
Custom coding your plug-in
To make a functional accordion, you must apply custom code to the jQuery plug-in function that you started creating in the previous section. The accordion plug-in starts by looping through all defined accordions. To define an accordion, use the following jQuery within the HTML document or within an externally embedded JavaScript file.
$('dl#my-accordion').accordion();
For each accordion, you access the associated definition titles using jQuery’s children
method, which returns an array or dt
elements. Apply a click
event to the dt
elements, then apply a method named reset
to each dt
. The reset
method collapses all dd
elements when the accordion first loads. The click
event triggers a custom method named onClick
when a dt
element or title bar is clicked. The custom onClick
method looks for all the dt
elements within the accordion. It calls a custom hide
method, which hides every associated dd
element by using the next
method to find the dd
element next to the dt
element, and then slides it up to animate it closed.
After all dd
elements are hidden, the dd
element associated with the clicked dt
element becomes visible using the slideDown
method and creates an expanding and contracting animation, as in Listing 8. The final line of code in the onClick
method is return false
, which ensures that any title bar that is clicked does not exhibit its usual behavior. For example, if you used an anchor
element as the title bar, you would want to return false
so the user isn’t directed to another page or portion of the existing page.
(function($) { $.fn.accordion = function(options) { return this.each(function() { var dts = $(this).children('dt'); dts.click(onClick); dts.each(reset); }); function onClick() { $(this).siblings('dt').each(hide); $(this).next().slideDown('fast'); return false; } function hide() { $(this).next().slideUp('fast'); } function reset() { $(this).next().hide(); } } })(jQuery);
When this accordion plug-in is associated with an HTML definition list structure like the one you previously created, the accordion function will be applied. With accordion functions, when one title bar or dt
element is clicked, its content area is opened and any other open content areas are closed. In other words, only one content area can be open at a time.
Defaults and options
A jQuery plug-in can include defaults and options. Options are essentially arguments that you can pass to your plug-in. Rather than sending several arguments, with options you can send one argument as an object literal, which is a standard jQuery practice. When allowing options in your plug-in, it is a best practice to set default options using the defaults
object. Like options, defaults are an object literal that should include the properties you are allowing to be passed to your plug-in.
For example, if you’re allowing a property that can be used to open the first content area of the accordion when it is first loaded, you should include a default for the open property within your plug-in. Use defaults within your plug-in to determine default functions and use options to override default values. When the plug-in receives the options, you can use the $.extend
method to do the actual overriding. jQuery’s $.extend
method merges two or more objects. The example in Listing 9 shows the common practice of using the $.extend
method to merge user-defined options with the default options in a custom jQuery plug-in.
(function($) { $.fn.accordion = function(options) { var settings = $.extend({}, {open: false}, options); return this.each(function() { var dts = $(this).children('dt'); dts.click(onClick); dts.each(reset); if(settings.open) $(this).children('dt:first-child').next().show(); }); function onClick() { $(this).siblings('dt').each(hide); $(this).next().slideDown('fast'); return false; } function hide() { $(this).next().slideUp('fast'); } function reset() { $(this).next().hide(); } } })(jQuery);
The $.extend
method arguments are a target object and two or more objects to merge. In the example, the target object is an empty object literal that acts as the container for the merged objects. The target will become a single object that includes the values of the merged objects—in this case, the settings
variable. The second argument is an object literal that includes the default plug-in properties. The third argument is the user-defined options argument. To pass options using the accordion plug-in on an HTML element, you need to know which properties the plug-in excepts before you can pass them as an object literal, as shown below.
$('dl#my-accordion').accordion({open:true});
In the example in Listing 9, the options that are passed to the plug-in override the defaults through the $.extend
method. If no options are passed, the default values are used. For the example plug-in, you use the open
property to determine whether the first content area should be open when it loads.
Reusability
You can reuse the example accordion plug-in in any HTML document, and can use it multiple times in a single HTML document. You can include multiple accordion structures, like the one already created, and define each separately as an accordion with jQuery using the new accordion plug-in you created. To add multiple accordions to an HTML document, simply add as many accordion structures as you desire. The code in Listing 10 includes two accordion structures separated by a paragraph.
<dl class="accordion" id="my-accordion"> <dt>Section 1</dt> <dd>Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam.</dd> <dt>Section 2</dt> <dd>Vestibulum a velit eu ante scelerisque vulputate.</dd> <dt>Section 3</dt> <dd>Nam mi. Proin viverra leo ut odio. Curabitur malesuada.</dd> <dt>Section 4</dt> <dd>Vivamus nisi metus, molestie vel, gravida in, condimentum sit amet, nunc.</dd> </dl> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> <dl class="accordion" id="my-accordion2"> <dt>Section 1</dt> <dd>Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam.</dd> <dt>Section 2</dt> <dd>Vestibulum a velit eu ante scelerisque vulputate.</dd> </dl>
The two accordion structures in Listing 10 are nearly identical, aside from their content and, more importantly, their ID values. The first structure includes an ID value of my-accordion
. The second structure includes an ID value of my-accordion2
. These structures can now be targeted independently from one another. For example, the following jQuery script defines each accordion structure as an accordion using the new plug-in you’ve created.
$('dl#my-accordion').accordion({open:true}); $('dl#my-accordion2').accordion({open:true});
Both accordion structures are defined, with the first panel set to open by default. Figure 3 shows an example of multiple accordion plug-ins being used in the same HTML document.
Putting it together
After you have created the new custom jQuery accordion plug-in, written the CSS, and put the HTML markup in place, you can put it all together into a final web page. To get the jQuery accordion plug-in working, you must embed the jQuery library. I prefer to use the content delivery network (CDN), which delivers the library based on the geographic location of the user and in turn delivers the file in the fastest way possible. Google includes the jQuery library on its CDN, and you can embed the file in your web pages using the URL https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
.
Other versions of the library are also available. See Resources for a link to the libraries on Google’s developer website. The only other files that you need to reference in your HTML document are the CSS file that styles the accordion and the jQuery accordion plug-in. After that, the HTML markup for the actual accordion structures will be transformed. Listing 11 shows an example.
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Creating a Custom jQuery Plugin</title> <link type="text/css" rel="stylesheet" href="jquery.accordion.css" /> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"> </script> <script type="text/javascript" src="jquery.accordion.js"></script> <script type="text/javascript"> $(document).ready(function() { $('dl#my-accordion').accordion({open:true}); $('dl#my-accordion2').accordion({open:true}); }); </script> </head> <body> <dl class="accordion" id="my-accordion"> <dt>Section 1</dt> <dd>Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam.</dd> <dt>Section 2</dt> <dd>Vestibulum a velit eu ante scelerisque vulputate.</dd> <dt>Section 3</dt> <dd>Nam mi. Proin viverra leo ut odio. Curabitur malesuada.</dd> <dt>Section 4</dt> <dd>Vivamus nisi metus, molestie vel, gravida in, condimentum sit amet, nunc.</dd> </dl> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> <dl class="accordion" id="my-accordion2"> <dt>Section 1</dt> <dd>Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam.</dd> <dt>Section 2</dt> <dd>Vestibulum a velit eu ante scelerisque vulputate.</dd> </dl> </body> </html>
Conclusion
In this article, you learned that it is fairly easy to create a custom jQuery plug-in. Any repetitive functions that you create can quickly be converted into a plug-in to speed up your development and increase efficiency. Reusability is the key to any plug-in, and reusability equals increased productivity.
Read the original article at IBM Developerworks
I truly agree with you, If you want to be more productive then you must have to customize the code with extending the core functions. Jquery has a poweful library so we can reuse the plugins from the library.
This is a great article. I have tried and it works.
Thanks for your work, Kris.