You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: page/plugins/basic-plugin-creation.md
+78-27Lines changed: 78 additions & 27 deletions
Original file line number
Diff line number
Diff line change
@@ -1,5 +1,5 @@
1
1
---
2
-
title : How to create a basic plugin
2
+
title : How to Create a Basic Plugin
3
3
level: intermediate
4
4
source: http://jqfundamentals.com/legacy
5
5
attribution:
@@ -9,19 +9,23 @@ Sometimes you want to make a piece of functionality available throughout your co
9
9
for example, perhaps you want a single method you can call on a jQuery selection that performs a series of operations on the selection. Maybe you wrote a really useful utility function that you want to be able to move easily to other projects.
10
10
In this case, you may want to write a plugin.
11
11
12
-
##How jQuery works 101
12
+
##How jQuery Works 101: jQuery Object Methods and Utility Methods
13
13
14
14
Before we write our own plugins, we must first understand a little about how jQuery works. Take a look at this code:
15
15
16
16
```
17
-
$('a').css('color','red');
17
+
var userColor = window.prompt('Please enter a color:', '');
18
+
$('a').css('color', $.trim(userColor));
18
19
```
19
20
20
-
This is some pretty basic jQuery code, but do you know what's happening behind the scenes? Whenever you use the `$` function to select elements, it returns an object. This object contains all of the methods you've been using (`css()`, `click()`, etc.), and all of the elements that fit your selector. The `$` function gets the methods from the `$.fn` object. This object contains all of the jQuery methods, and If we want to write our own methods, it will need to contain those as well.
21
+
This is some pretty basic jQuery code, but do you know what's happening behind the scenes? Whenever you use the `$` function to select elements, it returns a jQuery object. This object contains all of the methods you've been using (`css()`, `click()`, etc.), and all of the elements that fit your selector. The jQuery object gets these methods from the `$.fn` object. This object contains all of the jQuery object methods, and if we want to write our own methods, it will need to contain those as well.
21
22
22
-
##Basic plugin authoring
23
+
Additionally the jQuery utility method `$.trim()` is used above to remove any leading or trailing empty space characters from the user input. Utility methods are functions that reside directly on
24
+
`$` function itself. You may occasionally want to write a utility method plugin when your extension to the jQuery API does not have to do something to a set of DOM elements you've retrieved.
23
25
24
-
Let's say we want to create a plugin that makes text green. All we have to do is add a function called `greenify` to `$.fn` and it will available just like any other method.
26
+
##Basic Plugin Authoring
27
+
28
+
Let's say we want to create a plugin that makes text within a set of retrieved elements green. All we have to do is add a function called `greenify` to `$.fn` and it will available just like any other jQuery object method.
25
29
26
30
```
27
31
$.fn.greenify = function () {
@@ -31,50 +35,87 @@ $.fn.greenify = function () {
31
35
$('a').greenify(); // makes all the links green
32
36
```
33
37
34
-
Notice that to use `css()`, another method, we use `this`, not `$(this)`. This is because our `greenify` function is a part of the same object as `css()`.
38
+
Notice that to use `css()`, another jQuery object method, we use `this`, not `$(this)`. This is because our `greenify` function is a part of the same jQuery object as `css()`.
39
+
40
+
Additionally suppose we'd like to be more selective in our string trimming and provide for left trim (remove empty space characters at the beginning of the string) and right trim (remove empty space characters from the end of the string) methods. We can create `$.ltrim()` and `$.rtrim()` utility methods by attaching them directly to the `$` function:
41
+
42
+
```
43
+
// Attach ltrim and rtrim directly to the $ function
var myString = ' jQuery plugins are fun and easy! ';
48
+
console.log($.ltrim(myString));
49
+
console.log($.rtrim(myString));
50
+
```
51
+
52
+
jQuery's `$.extend()` method provides another alternative for creating new utility methods. When `$.extend()` is passed a single object, the contents of that object are merged with the `$` function.
53
+
54
+
```
55
+
// Have $.extend() attach ltrim and rtrim to the $ function
// $.ltrim and $.rtrim defined in this snippet behave
62
+
// the same as in the snippet above
63
+
var myString = ' jQuery plugins are fun and easy! ';
64
+
console.log($.ltrim(myString));
65
+
console.log($.rtrim(myString));
66
+
```
35
67
36
68
##Chaining
37
69
38
-
This works, but there's a couple of things we need to do for our plugin to survive in the real world. One of jQuery's features is chaining, when you link five or six actions onto one selector. This is accomplished by having all jQuery methods return the original jQuery object again (there are a few exeptions: `width()` called without parameters returns the width of the selected element, and is not chainable). Making our plugin chainable takes one line of code:
70
+
This works, but there's a couple of things we need to do for our plugin to survive in the real world. One of jQuery's features is chaining, when you link five or six actions onto one selector. This is accomplished by having all jQuery object methods return the original jQuery object again (there are a few exeptions: `width()` called without parameters returns the width of the selected element, and is not chainable). Making our plugin method chainable takes one line of code:
39
71
40
72
```
41
73
$.fn.greenify = function () {
42
74
this.css('color','green');
43
-
return this;
75
+
return this; // enables chaining with other jQuery object methods
44
76
}
45
77
46
78
$('a').greenify().addClass('greenified');
47
79
```
48
80
49
-
##Adding scope
81
+
Note that the notion of chaining is *not* applicable to jQuery utility methods like `$.trim()`.
82
+
83
+
84
+
##Protecting the $ Alias and Adding Scope
50
85
51
-
The `$` variable is very popular among javascript libraries, and if you're using one with jQuery, you will have to make jQuery not use the `$` with `jQuery.noConflict()`. However, this will break our plugin. To work well with other plugins, _and_ still use the jQuery `$`variable, we need to put all of our code inside of an [Immediately Invoked Function Expression](http://stage.learn.jquery.com/javascript-101/functions/#immediately-invoked-function-expression), and then pass the function `jQuery`, and name the parameter `$`:
86
+
The `$` variable is very popular among JavaScript libraries, and if you're using another library with jQuery, you will have to make jQuery not use the `$` with `jQuery.noConflict()`. However, this will break our plugin since it is written with the assumption that `$` is an alias to the `jQuery` function. To work well with other plugins, _and_ still use the jQuery `$`alias, we need to put all of our code inside of an [Immediately Invoked Function Expression](http://stage.learn.jquery.com/javascript-101/functions/#immediately-invoked-function-expression), and then pass the function `jQuery`, and name the parameter `$`:
52
87
53
88
```
54
89
(function ($) {
90
+
91
+
// We can safely use the $ alias inside the Immediately Invoked Function
In addition, the primary purpose of an Immediately Invoked Function is to allow us to have our own private variables. Pretend we want a different color green, and we want to store it in a variable.
63
104
64
105
```
65
106
(function ($) {
66
-
var shade = '#556B2F';
107
+
var shade = '#556B2F'; // private variable
67
108
68
109
$.fn.greenify = function () {
69
-
this.css('color',shade);
110
+
this.css('color',shade);
70
111
return this;
71
112
}
72
113
}(jQuery));
73
114
```
74
115
75
116
##Minimizing Plugin Footprint
76
117
77
-
It's good practice when writing plugins to only take up one slot within `$.fn`. This reduces both the chance that your plugin will be overriden, and the chance that your plugin will override other plugins. In other words, this is bad:
118
+
It's good practice when writing plugins to only take up one slot within `$.fn`. This reduces both the chance that your plugin will be overridden, and the chance that your plugin will override other plugins. In other words, this is bad:
78
119
79
120
```
80
121
(function ($) {
@@ -104,11 +145,15 @@ It would be much better to have one slot, and use parameters to control what act
104
145
}(jQuery));
105
146
```
106
147
148
+
<<<<<<< HEAD
107
149
##Using the each() method
150
+
=======
151
+
##Using the each() Method
152
+
>>>>>>> refresh basic plugins; added utility plugin method example
108
153
109
154
Your typical jQuery object will contain references to any number of DOM
110
155
elements, and that's why jQuery objects are often referred to as collections.
111
-
If you want to do any manipulating with specific elements (eg: getting data an
156
+
If you want to do any manipulating with specific elements (eg: getting an
112
157
attribute, calculating specific positions) then you need to use `each()` to
0 commit comments