One of the phases I went through while learning about JavaScript was the intense desire to write my own library, similar to jQuery (but massively scaled down).

My library has gone through several major revisions — and more than one complete re-write, but now is exactly what I started out hoping it would be: functional, clean, small, and a solid learning experience.

I’d like to share what I learned from this project, and I hope you share back with me through the comments!

Finished project demo

Step 1: Identify the purpose of your library

This might just be one of the toughest parts of the whole process! If you are to the point in your JavaScript knowledge that you would like to build your own library, than you’ve likely used jQuery, mooTools, Prototype, or any number of other popular libraries. I use jQuery extensively in my projects, and know that it is very capable in many aspects, including: animation, user input validation, AJAX loading/submitting, event handling, etc. Knowing this, it is tempting to have lofty goals for your own library. One piece of advice: Don’t.

Pick one particular function, or aspect of web development/design that you would like your library to handle. Pick a niche need, and be happy with yourself when you fill it.

I decided my library would be a simple way to manipulate elements visually. At this point, I didn’t quite know how — but all you need is the kernel of the idea.

Step 2: Mock-up how would use the library

You always mock-up a webpage before you start building it right? Whether on paper, Photoshop, or even in code, it helps to pretend what the finished product will look like before you build it. It helps you to see obvious bugs, conflicts, and unwanted interactions you don’t catch when looking at the problem mentally.

Have you ever mocked-up your code? Write some implementation, pretending that the class or object you are dealing with exists. Trust me, it will solve problems!

I want my library to do visual stuff with elements, and I like how jQuery looks. How about this?

$("#box").background("#ff0000").show(); 1 $ ( "#box" ) . background ( "#ff0000" ) . show ( ) ;

Looking at my pretend implementation, I can see 1 problem and a hand-full of design implementation points.

The problem: $ as a function name is likely to conflict with lots of other libraries. Through some Googleing, I learn at StackOverflow that functions must start with a $ (dollar-sign) _ (underscore) or letters.

_("#box").background("#ff0000").show(); // winner 1 _ ( "#box" ) . background ( "#ff0000" ) . show ( ) ; // winner

We can also tell some design patterns:

_ is the function name

is the function name _ must accept one or more parameters

must accept one or more parameters _ should return itself so that a dot-operator will work

should return itself so that a dot-operator will work _ must control its scope so that we can have more than one _() on a page

must control its scope so that we can have more than one on a page dot-operator methods must also return the _ object for chaining

Step 3: Code up an outline

At this point, we know enough about the goal of our library, and how we will implement it, to begin outlining the structure of our library.

// The `_` object constructor function _(id){ return this; } // our dot-operator methods _.prototype = { toggle: function () { // implementation return this; } }; 1 2 3 4 5 6 7 8 9 10 11 12 // The `_` object constructor function _ ( id ) { return this ; } // our dot-operator methods _ . prototype = { toggle : function ( ) { // implementation return this ; } } ;

It may be useful for some (me) to review javascript function/object prototyping.

Step 4: Fix-up the constructor

Now don’t try and run your code just yet: we have a pretty big scope issue (besides no functionality):

When our _() function returns this , it is actually returning the entire window, or the global scope. Therefore, when we call _().toggle() , we are asking the browser to call the toggle() method which belongs to the window. Obviously this fails.

This problem can be solved by recursively creating another _ object using the new keyword.

function _(id) { // Avoid clobbering the window scope: // return a new _ object if we're in the wrong scope if (window === this) { return new _(id); } return this; }; 1 2 3 4 5 6 7 8 function _ ( id ) { // Avoid clobbering the window scope: // return a new _ object if we're in the wrong scope if ( window === this ) { return new _ ( id ) ; } return this ; } ;

For an in-depth look at this problem, read more about JavaScript constructors

Next to implement in our constructor: making the _() represent an element with some bonus error prevention.

First, we create an about object that will be returned, if the implementation doesn’t specify an element id. Next, we check if the id parameter was sent, and then create a variable to contain that element.

Here is a final version of the _() constructor:

function _(id) { // About object is returned if there is no 'id' parameter var about = { Version: 0.5, Author: "Michael Jasper", Created: "Fall 2010", Updated: "23 November 2011" }; if (id) { // Avoid clobbering the window scope: // return a new _ object if we're in the wrong scope if (window === this) { return new _(id); } // We're in the correct object scope: // Init our element object and return the object this.e = document.getElementById(id); return this; } else { // No 'id' parameter was given, return the 'about' object return about; } }; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 function _ ( id ) { // About object is returned if there is no 'id' parameter var about = { Version : 0.5 , Author : "Michael Jasper" , Created : "Fall 2010" , Updated : "23 November 2011" } ; if ( id ) { // Avoid clobbering the window scope: // return a new _ object if we're in the wrong scope if ( window === this ) { return new _ ( id ) ; } // We're in the correct object scope: // Init our element object and return the object this . e = document . getElementById ( id ) ; return this ; } else { // No 'id' parameter was given, return the 'about' object return about ; } } ;

Step 5: Prototype method implementation

This step is pretty fun: being creative, and implementing what you want your library to actually do!

I mentioned earlier that I wanted my library to do some visual manipulation of elements. Make a list of what you want to do. I came up with the methods:

hide ()

show ()

bgcolor (color)

val (value)

toggle ()

size (height, width)

The depth of this step depends on the functionality of your library. Mine were rather trivial to implement:

/* _ Prototype Functions ============================*/ _.prototype = { hide: function () { this.e.style.display = 'none'; return this; }, show: function () { this.e.style.display = 'inherit'; return this; }, bgcolor: function (color) { this.e.style.background = color; return this; }, val: function (newval) { this.e.value = newval; return this; }, toggle: function () { if (this.e.style.display !== 'none') { this.e.style.display = 'none'; } else { this.e.style.display = ''; } return this; }, size: function (height, width) { this.e.style.height = height + 'px'; this.e.style.width = width + 'px'; return this; } }; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 /* _ Prototype Functions ============================*/ _ . prototype = { hide : function ( ) { this . e . style . display = 'none' ; return this ; } , show : function ( ) { this . e . style . display = 'inherit' ; return this ; } , bgcolor : function ( color ) { this . e . style . background = color ; return this ; } , val : function ( newval ) { this . e . value = newval ; return this ; } , toggle : function ( ) { if ( this . e . style . display !== 'none' ) { this . e . style . display = 'none' ; } else { this . e . style . display = '' ; } return this ; } , size : function ( height , width ) { this . e . style . height = height + 'px' ; this . e . style . width = width + 'px' ; return this ; } } ;

Demo or download the finished library here

Final thoughts

Writing my own small library was a good way for me to learn about JavaScript. One of the great ways to learn more is to study the code of other libraries and see how they work.

Did you use this tutorial to create your own library? I would really like to hear about it. Please leave me a comment below.

Cheers!

Update

Stack Overflow user W3Geek asked a question about part of this tutorial. Visit his question: How do these pieces of code function exactly? His question is focused on Step 4 about the object constructor. User Leland Richardson does an excellent job explaining this further — I’d direct you to his thorough explanation rather than duplicating it here.