Welcome to the 20th Easy jQuery Tutorial, part of EasyProgramming.net. Did you know that you can extend jQuery with your own custom plugins? In this tutorial, that's what we'll explore.
jQuery is already very powerful, but it lets you add onto the library and create plugins that you can use and that others can use. I show you a very easy and quick way of understanding how to create plugins in jQuery.
A quick example of what a custom plugin looks like:
$.fn.methodName = function(options) { let settings = $.extend({ property1: value1, property2: value2 }, options); return this.css(settings); }
We start the plugin method with $.fn
which is just telling jQuery that we are creating a custom function (aka method). The methodName is the actual name of the plugin that we want to use. In the video below, I show you two different examples.
We then create an anonymous function which can take user inputted options
. We then define default values for those options in the settings
variable by assigning an object created with the jQuery $.extend()
method.
Then when we are done, we simply return this
, where this
is the contex in which the method is applied.
You can create as many of these as you'd like and store it in a .js file. Then these can be reused over and over again.
I hope you enjoyed this tutorial! Please feel free to ask questions below or just leave your comments.
To fork the fiddle and follow along: https://jsfiddle.net/easyjs/Lo7jvhag/
Remember to checkout the Resources section below for associated downloadable content, JSFiddle links, and other resources. Watch the video and follow along!