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 See the source code for the examples used in this article.
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 JavaScriptprototype
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.Listing 1. Defining a new jQuery plug-in named accordion
jQuery.fn.accordion = function() { // Add plugin code here };
$
). 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.
Listing 2. Wrapping a new jQuery plug-in named accordion in a wrapper function
(function($) { $.fn.accordion = function() { // Add plugin code here }; })(jQuery);
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 thethis
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.
Listing 3. Using the return
keyword
in front of the each
loop
(function($) { $.fn.accordion = function() { return this.each(function() { // Using return allows for chainability }); }; })(jQuery);
$("#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.
Listing 4. A single chain of method calls
<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>
Listing 5. Accordion CSS class used to define styles for the overall definition list
.accordion { width: 500px; border: 1px solid #ccc; border-bottom: none; font-family: Arial, Helvetica, sans-serif; font-size: 12px; }
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.
Listing 6. Shared styles associated with titles and content areas of the accordion
.accordion dt, .accordion dd { border-bottom: 1px solid #ccc; margin: 0px; }
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.
Listing 7. CSS classes associated with title and content areas of the accordion
.accordion dt { background: #eaeaea; cursor: pointer; padding: 8px 4px; font-size: 13px; font-weight: bold; } .accordion dd { padding: 12px 8px; }
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();
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.Listing 8. Custom accordion functions used to create a jQuery plug-in
(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);
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.
nice :)
ReplyDelete