If you are JavaScript Developer, you probably know jQuery. But do you know how to use it to create your own JQuery Plugin? Read on to get started!
For those who don’t know, JQuery is a JavaScript library that comprises of a number of features, and is quite small yet fast. It also comprises of an easy-to-use API that is compatible on all browsers and enables easier HTML traversal, animation, DOM manipulation, and event handling. It is not only extensible but durable. Hence, client-side scripting has become a lot easier since its development.
What Are JQuery Plugins?
JQuery consists of prototype objects which may require some manipulation and extension. For the same purpose, JQuery plugins were devised as a way for objects to inherit any additional methods that are added. Not only that, these additional methods are not isolated but called with the rest of the methods (already inherited) when the JQuery object is created. JQuery plugins are available individually in the form of individual methods that exist in the JQuery library. Every method is a plugin. But, in case of something new, the plugin can also be custom created, which is not very difficult a task.
How Does JQuery Work?
To understand how JQuery works, you need to follow these steps:
- Create an HTML document with all the basic tags and calling the JQuery.js file.
- Developers think ahead and encapsulate the executable commands of the code into an
onload()
function in order to ensure that the commands execute as soon as the document is loaded into the browser. - At times, due to the delay in the loading of images, the document is not loaded in its entirety. To ensure that the complete document is ready to be worked on after loading, developers supply a
ready
event into their code. - The complete script for the
ready
event, with the function encapsulated in it, is put inside the HTML document created earlier. Saving and running the document will ensure that your code executes with an output. - This function could contain any event (sub-events) or commands to perform a certain task.
What Is the Basic Plugin Signature?
$.fn.pluginName = function() { this.css( "color", "yellow" ); }; $( "a" ).pluginName();
The plugin starts its identity creation as shown above. pluginName
is replaced by the name of your plugin that is being created, followed by a function and any required parameters in the brackets. Further on, the next statement inside the function (this.css
) is ensuring that the CSS is applied to certain text to make it yellow in color. The last line calls the plugin function to turn all the links with ‘a
’ tag yellow.
Protecting the $Alias and Adding Scope
A jQuery plugin is always written with an assumption that using $
is using an alias of jQuery function. $
is quite famous among JavaScript libraries. So, when more than one jQuery library is required, a conflict may arise with the use of $
. Therefore, to enable us to use jQuery with other plugins along with $
, we must place the code inside the expression of the immediately invoked function. This is followed by the passing of jQuery and then naming its parameter $
.
Adding Private Methods and Variables
In JavaScript, functions contain several variables and other functions that can be mainly accessed inside the function thereby making the elements private. Immediately invoked function efxpressions provide the best way to access private variables and methods.
Adding private methods or variables can be understood here after the alias ($
) matter is resolved:
(function($) { $.fn.pluginName = function() { // private variables var privatevar1 = ''; var privatevar2 = ''; // private methods var myPrivateMethod = function() { // do something ... } })(jQuery);
Adding a private variable and enabling its use is only possible through the Immediately Invoked Function:
(function($){ var col = “yellow”;$.fn.pluginName = function() { this.css("color", col); return this; }; }(jQuery));
Private methods can only be called from within the scope of the function. Only other private methods or public methods have the authority to call these private methods. This also goes for accessing the private variables.
Adding Public Methods
Adding methods to jQuery plugins is done as it is done in private methods. The only difference is the execution of the method. When the method is supplied with a ‘this
’ operator, the method becomes public. This way it can also be accessed outside the scope of the function. The purpose of adding such public methods could be either to perform a function outside the scope or to access the public variables and methods from outside the scope.
(function($) { $.fn.pluginName = function() { // public methods this.initialize = function() { // do something ... return this; }; this.myPublicMethod = function() { // do something ... }; })(jQuery);
Accepting Options for Plugin Customization
There are cases where your plugins start becoming complex, as you continue to add to them. Therefore, it is a good idea to make your plugin start accepting some options and make them customizable.
(function($) { $.fn.pluginName = function(options) { var defaults = { color: "white", 'background-color': "#556b2f" }; var settings = $.extend({}, defaults, options); return this.css({ color: settings.color, 'background-color': settings.background - color }); }; }(jQuery));
Putting it All Together
Combining all methods, the following example plugin is compiled:
(function($) { $.fn.pluginName = function(options) { var defaults = { color: "white", 'background-color': "#556b2f" }; var settings = $.extend({}, defaults, options); if (this.length > 1) { this.each(function() { $(this).pluginName(options) }); return this; } // private variables var privatevar1 = ''; var privatevar2 = ''; // private methods var myPrivateMethod = function() { // do something ... } // public methods this.initialize = function() { // do something ... return this; }; this.myPublicMethod = function() { // do something ... }; return this.initialize(); } })(jQuery);
Here, the method ‘each()
’ is used to loop through a collection of elements. Also, the return value for this method is the this.append()
method, which accepts the callback where upon its return we will be able to see what element is being appended to in the collection.
alternative to antihistamine for allergy best generic allergy pills doctor prescribed allergy medication
sleeping pills prescription online buy modafinil 100mg pill
generic prednisone 5mg order prednisone 10mg
what painkiller helps stomach pain buy baycip tablets
clear skin image pills deltasone 10mg pills best acne medication for men
is omeprazole a promotility drug amaryl 1mg over the counter
absorica over the counter order absorica pill buy accutane 40mg pills
order amoxil 250mg sale amoxicillin us generic amoxicillin 1000mg
online sleep medication perscriptions order phenergan 10mg generic
zithromax 500mg cheap azithromycin usa buy azithromycin 250mg generic
neurontin 800mg cheap brand neurontin 800mg
buy azithromycin without prescription azipro 500mg uk azithromycin brand
lasix ca furosemide 100mg price
I’m not that much of a internet reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your website to come back down the road. Many thanks
buy generic omnacortil over the counter buy generic omnacortil for sale order generic omnacortil 20mg
amoxicillin 500mg cheap amoxil 500mg us cost amoxicillin
buy doxycycline 100mg online doxycycline 100mg generic
order albuterol 2mg online order ventolin 2mg without prescription order albuterol generic
augmentin online amoxiclav oral
how to get levothyroxine without a prescription cheap synthroid 75mcg order synthroid 150mcg
where to buy levitra without a prescription order generic levitra 20mg
buy generic clomid 50mg order clomiphene 50mg without prescription buy clomiphene 50mg generic
buy tizanidine buy zanaflex pills how to get zanaflex without a prescription
prednisone 40mg canada buy prednisone 5mg online cheap buy prednisone 5mg for sale
order rybelsus 14mg pill rybelsus buy online rybelsus 14 mg pills
buy generic accutane 10mg buy isotretinoin 20mg generic cost accutane
rybelsus 14mg pill semaglutide oral buy semaglutide 14mg online cheap
brand amoxicillin 250mg cheap amoxil brand amoxil 250mg
generic albuterol albuterol drug purchase albuterol online cheap
generic zithromax order zithromax 250mg pill order zithromax 250mg pill
augmentin 375mg uk order generic augmentin augmentin drug
order generic prednisolone omnacortil ca buy prednisolone 40mg online
synthroid 100mcg ca buy levothroid online cheap synthroid 150mcg pills
Gdy zapomnisz hasła do zablokowania ekranu, jeśli nie wprowadzisz prawidłowego hasła, odblokowanie i uzyskanie dostępu będzie trudne. Jeśli okaże się, że Twój chłopak / dziewczyna jest podejrzana, być może pomyślałeś o włamaniu się do jego telefonu Samsung, aby uzyskać więcej dowodów. Tutaj zapewnimy Ci najlepsze rozwiązanie, jak złamać hasło telefonu komórkowego Samsung.
gabapentin 100mg without prescription order neurontin 600mg pills order gabapentin 100mg online
clomiphene 100mg drug serophene cheap buy cheap clomiphene
buy furosemide paypal cheap lasix 100mg buy furosemide pills for sale
Jeśli myślisz o użyciu aplikacji szpiegowskiej na telefon komórkowy, dokonałeś właściwego wyboru.
sildenafil otc order viagra 50mg sale canadian viagra and healthcare
purchase vibra-tabs online buy doxycycline 200mg pill doxycycline 100mg generic
purchase rybelsus sale buy semaglutide 14mg for sale buy rybelsus 14 mg pill
online roulette for real money play blackjack casino online games for real money
Cialis Generico Compra Segura
It is remarkable, very amusing piece
Cialis 5 mg prezzo cialis 5 mg prezzo cialis 5 mg prezzo
levitra pill order levitra 20mg sale vardenafil online
generic pregabalin 150mg buy pregabalin 75mg for sale cost lyrica 150mg
order triamcinolone sale triamcinolone 10mg pills brand aristocort 10mg
order hydroxychloroquine pill plaquenil cost buy plaquenil for sale
zithromax pregnancy category
cost desloratadine order desloratadine 5mg generic buy clarinex 5mg pill
tadalafil online tadalafil 10mg pills cialis usa
Aviator Spribe играть выгодно казино
I consider, that you are not right. I can prove it.
Получайте удовольствие от игры с автоматом Aviator Spribe играть казино и зарабатывайте крупные выигрыши!
cenforce 100mg pills oral cenforce buy cenforce 100mg sale
buy generic claritin buy claritin 10mg online loratadine for sale online
brand aralen 250mg chloroquine online order buy aralen 250mg
dapoxetine 60mg cheap order cytotec pills buy generic cytotec
diabetes metformin
buy orlistat 60mg online cheap order diltiazem generic order diltiazem 180mg sale
buy metformin pills buy metformin 500mg sale buy metformin 1000mg without prescription
how much furosemide can you take in a day
zoloft addiction
dosage of flagyl for dogs
buy acyclovir 400mg pill order zovirax 400mg without prescription purchase allopurinol generic
lisinopril vs hydrochlorothiazide
buy amlodipine no prescription buy generic norvasc for sale order norvasc pill
lasix kidney function
glucophage crush
zithromax strep throat
crestor 20mg generic ezetimibe 10mg for sale buy ezetimibe without prescription
lisinopril for sale generic prinivil buy lisinopril 10mg pills
can you take gabapentin with tylenol
buy cheap generic motilium buy motilium tablets buy sumycin cheap
I blog often and I genuinely appreciate your content. Your article has truly peaked my interest. I am going to book mark your site and keep checking for new details about once a week. I opted in for your RSS feed as well.
bitcoin price live
amoxicillin for kids
dosage of gabapentin for dogs
buy generic omeprazole prilosec ca buy generic prilosec for sale
escitalopram controlled drug
cyclobenzaprine over the counter flexeril medication baclofen us
lopressor oral where to buy lopressor without a prescription buy metoprolol 50mg for sale
bactrim class
can i take ciprofloxacin during menstruation
bactrim ds tablet uses
ketorolac drug order colcrys 0.5mg generic buy colcrys 0.5mg for sale
atenolol canada purchase atenolol generic brand atenolol 100mg
antibiotics cephalexin
Не упустите возможность воспользоваться выгодными ценами на услуги гипсокартонщика в Алматы. Закажите услугу уже сегодня и убедитесь в профессионализме наших мастеров!
medrol 8mg over counter methylprednisolone pills medrol 8 mg tablets
inderal online buy plavix for sale clopidogrel 75mg sale
order essays online buy an essay paper help with papers
buy methotrexate 10mg pill methotrexate price buy coumadin tablets
can i take amoxicillin while pregnant
reglan cost losartan cost losartan ca
Откройте для себя официальный сайт https://vigrat.ru казино Vegas Grand и наслаждайтесь игровыми автоматами онлайн!
cheap meloxicam meloxicam 7.5mg ca celebrex 100mg over the counter
nexium 40mg cheap buy topiramate cheap oral topiramate 100mg
gabapentin and ibuprofen
escitalopram oxalate 10mg tablet
flomax 0.4mg cheap where to buy celebrex without a prescription buy celecoxib 100mg online
buy imitrex 50mg pills levaquin 250mg us levofloxacin 250mg ca
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
buy zofran without prescription aldactone ca aldactone 25mg generic
order avodart 0.5mg generic order zantac 300mg for sale zantac canada
citalopram ocd
simvastatin 20mg over the counter generic valacyclovir 1000mg valtrex 500mg oral
ddavp and clopidogrel
what is cozaar medication
ampicillin pills ampicillin drug buy amoxil medication
buy finasteride 5mg generic finasteride 1mg generic buy fluconazole 200mg pill
how long does depakote take to work
Hi, for all time i used to check website posts here early in the break of day, as i enjoy to gain knowledge of more and more.
https://maps.google.hk/url?q=https://hottelecom.biz/hi/
buy ciprofloxacin no prescription – purchase bactrim without prescription augmentin 1000mg pills
buy cipro sale – order cephalexin online cheap order augmentin generic
what antihistamine can i take with citalopram
tenormin 100 and cozaar 50 together
efeitos colaterais do ddavp
ciprofloxacin 500mg pills – erythromycin 500mg over the counter purchase erythromycin for sale
depakote blood test
I would like to talk to you, to me is what to tell on this question.
Подробно расскажем, как Выселить из жилого помещения – Бабаевский районный суд Вологодской области онлайн или самостоятельно Выселить из жилого помещения – Бабаевский районный суд Вологодской области Выселить из жилого помещения – Бабаевский районный суд Вологодской области онлайн или самостоятельно
flagyl 200mg usa – cheap azithromycin buy azithromycin tablets
Para Que Sirve El Tadalafil De 5 Mg
Certainly. It was and with me.
Cialis 5 mg prezzo cialis 5 mg prezzo cialis 5 mg prezzo
I have thought and have removed this question
аренда номера для смс
atorvastatin ezetimibe clinical trials
augmentin suspension
buy stromectol europe – buy generic sumycin online purchase sumycin online
what is diltiazem hydrochloride