Create your own plugin, why not?

Interactive elements (such as sliders, galleries or interactive menus) are very familiar objects for a developer. You can manually create these elements for each site. But imagine, how much time will you save when you can pack this into a handy jQuery plugin?

In the article, we will learn how to build your own jQuery plugin. You will know the necessary conditions to produce a quality and effective plugin quickly.

Next, to show different parts of a plugin, we will use fancytoggle . This is a simple template plugin, used to toggle display nested elements (like list items), and to create accordion-style widgets for sections like FAQs. In general, the idea is based on the most basic concept needed in plugins, the following example will show you this link in practice.

See the Pen FancyToggle by SitePoint ( @SitePoint ) on CodePen .

Benefits from using the plugin

Here, the main purpose is to create a handy extension tool, which we can add to the project. And the plugin function of jQuery will partly help us simplify many tasks.

One advantage of these plugins is: programmers can determine which options to customize functionality. You can completely add some options that can completely change the way a plugin works, or you can use just enough options to let users choose the desired styling and layout. With plugins, you can do everything at your disposal.

Develop jQuery Plugins

Take a look at the steps to do to register the new jQuery plugin. We will continue to use the fancyToggle plugin as an example.

Creating our function with $ .fn

jQuery plugins work by registering a function with the name you want to call to activate the plugin (for example, you will call the inbuilt function .width () or .height () to return width / dimension results. quit)

We will assign the function to the $ .fn object in jQerry so we can use the function on the $ global object. Thus, our function is registered and can be called on objects or selections.

Just that simple! So far we have added a new call method that is customizable from the $ object of jQuery. Eg:

With $ .fn, you want to register as many functions as you want. However, you should avoid registering more than a function, unless the plugin is for a completely different job.

Nhiều tập tin và looping

Remember, when you call your plugin, the plugin can apply itself to one or more elements. For example, if we apply fancytoggle () to various items, our function will have to handle the collection.

To handle each element, we just need to iterate through the collection with the $ .each function in jQerry:

Just repeat the same with each element in the collection. With $ .each, even if you have to do calculations, add the event listener, … more, it will still ensure that we will refer to the right element.

Pay objects / chaining

In most cases, when you directly call the plugin on an object or selector, the plugin's feature will run on that item.

In jQerry, we also have the concept of chaining, with chaining you can constantly call a series of methods on a single item and each method will execute in the following order:

The chaining process will direct an element, adding the active class and pushing the element up or down. Each method will return an object, this obejct continues to be called by the next method.

In order for the plugin to work this way, we only need to return the item at the end of the function of the plugin. This step is highly recommended, although technically, you do not need to do so.

Create options and configurations

Through a variety of options, the plugin's behavior can be changed. These options, in the form of key / value pairs (an object type in JavaScript), will change your function:

In order for our plugin to be able to handle options, we need to determine how to use the default setting. Then, we can use the $ .extend method to associate our default option with the submitted options when the plugin is called:

You can freely create numerous options for your plugin $ .extend will create a single object by combining and collecting values. You should add some basic settings or elements to help the plugin "install itself".

With the plugin we are building, we need some options to determine how the plugin will work. For example, we want users to toggle open areas as desired. However, we can also customize them to only be toggle each section one by one (and close other sections). While executing the toggle function, we will check to see if we should close other items, based on this setting.

Event listeners

Event listeners are functions that are called at specific events in the plugin life cycle. These callbacks will help others understand the key parts of your plugin immediately and can enable the functionality of the plugin.

Many jQuery plugins also have similar callbacks like this; for example when clicking through the slide-show or closing the modal window.

You will define these callbacks as elements for the default option. Start by adding these event names or setting their values ​​to empty functions:

Instead of using all of the empty functions, jQuery also provides the function $ .noop . This function has a similar role, but you should pay attention to resources when creating multiple anonymous functions.

Once the settings have been optimized, you can start building the function at the time the callbacks occur.

Callbacks work by calling your options when enabled. For example, in our plugin, we have a onItemClick callback that needs to be activated every time someone clicks on toggle item. Next, we will use the call method to activate the event listener (if there is already a previous set).

Take a look:

Thus, when we toggle items, we move the three parameters. The first parameter is null: we do so for later, when we expand the callback there is no need to worry about the value of this.

The second parameter is $ item (the element toggled): this is a pretty important parameter because this parameter gives access to the item itself to the callback function.

Finally, we have the event parameter (which is also the event we are talking about).

The event listener will have access to both $ item and event; at the same time can adjust our function. For example, if we want to remove the element when clicked:

This is one of the many reasons why events are so flexible. The event can help developers access the plugin at additional points, so that it can be expanded or changed to suit specific needs.

progressive enhancement

So, the question to ask is: what if JS is disabled? Without JS, our plugin will not work.

For example, when you create toggleable sections with title and content body (click on title to toggle body running up and down). If we don't open JS, cotent still works as usual.

Notice the above situations to avoid unexpected incidents.

You want more?

Expand knowledge

With the basic knowledge introduced in this article, I believe that you must have somewhat been able to produce simple but equally effective plugins for your next projects. To further improve the plugin, you can learn more about other plugin development. In particular, jQuery's website itself has many good sections in this respect .

Dig into the plugin

The best way to learn is to practice. Only when you start working, do you realize your shortcomings and strengths.

You can also check out and experiment with fancytoggle examples in the article, you can learn more about this template plugin on CodePen. You can:

  • Add new option to default arguments (and possibly override)
  • Add an event to the plugin (like when toggle area resize or after the plugin starts)
  • Use existing events to extend plugin functionality (eg enable fade-in animation when a section opens and dims when closed)

Summary: what is the article

  • Add plugin to jQuery namespace with $ .fn
  • Process multiple collections with the .each loop
  • How to create a chain method
  • How to create default options and combine options with transferred custom values
  • How to take advantage of callback to give access to plugin developer features
  • Preliminary study of progressive enhancement (case when JS cannot be used)

ITZone via sitepoint

Share the news now