Creating Your First JQuery Plugin

Why Actualize a jQuery plugin

Sometimes its is advantageous to accept a area of functionality accessible throughout your code. Maybe you wish a individual activity you can alarm on a jQuery selector that performs a specific activity on such selector. Or maybe you wrote a account activity in one of your projects and now you wish to be able to move it calmly to added projects. In any case autograph a plugin is your best option.

jQueryis great. It’s cross-browser, simple to learn, and helps you accomplish absolute convenient interfaces. It aswell comes with a lot of advantageous plugins to do about whatever you want.

But sometimes a lot is not enough, what if you can’t acquisition just the appropriate plugin to clothing your needs? Or maybe there abide a plugin but its too large, and you just wish allotment of it. The band-aid ability be to cycle up your selves and address your own stuff. After all it complete added complicated than it absolutely is. This abbreviate tutorial will go through the action of autograph a simple plugin, abacus some options, and even accomplish a callback.

Setting Up

You can download the absolute activity from GitHub

For this tutorial, we will be creating a simple accordion plugin. Let’s actualize a js book and put it in the “js” agenda of our website. It’s attitude to alpha all js plugin’s files with “jquery dot” followed by the absolute plugin name, so we’ll alarm ours “jquery.simple-accordion.js”.

- Our plugin book central the js agenda central our website directory

Now we charge to cover our plugin book forth with the jQuery library to our capital HTML page (index.html). It is best convenance to cover the jQuery library anon from the Google api servers, back they are broadcast beyond the apple instead of your individual server location: Closer servers usually agency faster acknowledgment times for the visitor. Accession advantage of accepting jQuery included from Google, is that if a company comes to your website they may already accept the jQuery Software in their bounded cache. Pre-cached agreeable usually agency faster amount times for the visitor.

The jQuery Plugin Structure

jQuery is arranged with all the all-important hooks to aid you in the development of our plugin. But is acceptable to accumulate up the JavaScript acceptable practices, so we accept to accomplish abiding aggregate is kept central a bounded scope. Let’s alpha with the basal carapace of a jQuery plugin:

(function($) {

$.fn.simpleAccordion = function() {

//TODO: cipher for simple accordion plugin

}

}(jQuery));

Let’s bound go through what’s traveling on here. By including aggregate in the (function() {}) self-enclosed JavaScript pattern, we’re authoritative abiding that all the variables in our plugin will break cautiously alfresco of the all-around namespace. We don’t to run into conflicts with any added javascript active in this page, so we accept to abstract our cipher as we did above.

The added affair you ability apprehension is that we’re defining our plugin as if jQuery was in it’s “no-conflict” mode. Again, we’re gluttonous to abstain colliding with added JavaScript on the page, and appropriately we wish to accomplish abiding that our plugin isn’t codicillary on the absence $, which could be acclimated by accession library.

Finally, $.fn is jQuery’s way of acceptance you to ascertain our plugin, which we’ve called simpleAccordion. With all of our pieces in place, let’s get cooking!

Adding Functionalities to Our Plugin

What is abundant about jQuery is that it lets you use any selector you want. However, you accept to accumulate in apperception that our constituent can be ambidextrous with several altered aspect types. Application the “this” keyword lets our constituent administer the associated functions by accessing anniversary aspect in a bend behindhand of the aspect type.

Getting The HTML Allotment Ready – Structuring The Accordion

Since we are architecture an accordion we are traveling to charge to HMLT anatomy for it, so actuality we go:

Heading 1

Cras agony elit, porttitor ac diam bibendum, eleifend aliquam erat.

Heading 2

Donec blandit risus nec est tristique interdum.

Heading 3

Fusce sit amet arcu id justo malesuada faucibus.

Heading 4

Aliquam tincidunt lobortis sem at porttitor.

This is a simple accordion structure, defining four titles and their corresponding agreeable areas. So the abstraction is that our plugin will about-face this HTML cipher into a anatomic accordion, area an user can accessible and collapse altered sections.

This is how it should attending like for now:

Just to accomplish it attending appealing we should add some simple styles. So actuality we go:

.accordion {

width: 600px;

border: 1px solid #ccc;

border-bottom: none;

}

.accordion dt,.accordion dd {

border-bottom: 1px solid #ccc;

margin: 0px;

}

.accordion dt {

background: rgba(193, 221, 252, 0.24);

cursor: pointer;

padding: 8px 4px;

font-size: 14px;

font-weight: bold;

}

.accordion dd {

padding: 12px 8px;

}

Now our accordion anatomy should attending like this:

The jQuery Allotment – Time To Accomplish It Do Something!

To add functionality to our plugin we are traveling to adapt the js book and add the afterward code:

(function($) {

$.fn.simpleAccordion = function(options) {

return this.each(function() {

var dts = $(this).children(‘dt’);

dts.click(accordionClick);

dts.each(reset);

});

function accordionClick() {

$(this).siblings(‘dt’).each(hide);

$(this).next().slideDown(‘fast’);

return false;

}

function hide() {

$(this).next().slideUp(‘fast’);

}

function reset() {

$(this).next().hide();

}

}

})(jQuery);

Quickly let’s go over what this cipher is doing. First, you charge to accept that jQuery is a library that extends the JavaScript language. If creating any jQuery plug-in, you’re about extending the jQuery library, which is extending JavaScript. Truly compassionate how your constituent extends the jQuery library requires an compassionate of the JavaScript ancestor property. Although it is not acclimated directly, the JavaScript ancestor acreage is acclimated abaft the scenes through the jQuery acreage fn, which is a jQuery alias for the built-in JavaScript ancestor property.

So in simpler terms, you extend your plugin from jQuery by application fn.”your-plugin-name”

In addition, we could add options to canyon to our plugin. A jQuery constituent can cover defaults and options. Options are arguments that you could canyon to your plug-in. Rather than sending several arguments, with a options article you can forward assorted properties, which is the accepted jQuery practice. If acceptance options in your plug-in, it is a best convenance to set absence options application the defaults object. Like options, defaults are an article accurate that should cover the backdrop you are acceptance to be anesthetized to your plug-in.

Let’s bound add some options to our plugin to appearance how simple this is. We are traveling to canyon an advantage constant to accessible the aboriginal area of our accordion if it is aboriginal loaded.

(function($) {

$.fn.simpleAccordion = function(options) {

var accompaniment = $.extend({}, {open: false}, options);

return this.each(function() {

var dts = $(this).children(‘dt’);

dts.click(accordionClick);

dts.each(reset);

if(state.open)

$(this).children(‘dt:first-child’).next().show();

});

function accordionClick() {

$(this).siblings(‘dt’).each(hide);

$(this).next().slideDown(‘fast’);

return false;

}

function hide() {

$(this).next().slideUp(‘fast’);

}

function reset() {

$(this).next().hide();

}

}

})(jQuery);

If you notice, we are application absence amount of open:false, so if no advantage is passed, the plugin will accept that you wish your accordion bankrupt if aboriginal loaded. If the constituent receives options, you can await on the $.extend adjustment to do the absolute overriding. What the $.extend adjustment does is that it merges two or added objects.

That’s it!

So there you accept it your aboriginal jQuery plugin, absolute simple right. I achievement you enjoyed this tutorial, and acquisition it useful. You can download the absolute activity from GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>