11/27/2018

jQuery Plugins

jQuery Plugins

jQuery plugins provide developers an easy way to create reusable code. There are hundreds of existing plugins, but you can improve your JavaScript skills by writing your own.

Basic Structure


    $.fn.PluginName = function () {
        elms = this;
    }
    $('span').PluginName();
        

'$' is the jQuery base object. fn is like prototype in JavaScript.

Example

See the Pen YYoyWJ by Jon (@Middaugh) on CodePen.

Customization

Plugins become more helpful when you are able to leverage their customization. We can customize options by using the jQuery extend function.

How to add customization


    $.fn.PluginName = function (options) {
        elms = this;
        //Outputs black
        console.log(options.color);
    }
    $('span').PluginName({color: '#000'});
        

What about optional options?

We can leverage jQuery's $.extend method to merge your options.

Extend

See the Pen jQuery Extend by Jon (@Middaugh) on CodePen.

Passing an empty object as the target preserves the original objects.

Extend API Docs

In a Plugin

See the Pen Basic jQuery Plugin by Jon (@Middaugh) on CodePen.

Unique events

See the Pen Basic jQuery Plugin Basic Events Each by Jon (@Middaugh) on CodePen.

Web Storage

Session Storage

Stores data for one session (data is lost when browser is closed).

Local Storage

Stores data with no expiration date.

W3Schools Example


    if(typeof(Storage) !== "undefined") {
		localStorage.setItem("lastname", "Smith");
	}else{
		//Some graceful fallback plan
	}
	
        

You can use this to mock a back end on demo day, but....

Never store sensitive data in web storage. If a malicious script were to run in your browser, it can access web storage and send the data anywhere.

Other Mock Data Solutions

There are a number of solutions for mocking data in your app. This can also be known as backendless development.

  • Create local .json files that contain/save mock data.
  • Find a library built for backendless development. This is one example: Angular 6 backendless dev

Make a jQuery plugin for your site.

>