Creating your own JavaScript Library

Share on Facebook14Share on Reddit0Tweet about this on Twitter24Share on Google+23

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?

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.

We can also tell some design patterns:

  • _ is the function name
  • _ must accept one or more parameters
  • _ 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
  • 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.

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.

What is the new keyword in JavaScript?

 

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:

 

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:

 

Demo or download the finished library here

Part 2 – Event Handling

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.

Share on Facebook14Share on Reddit0Tweet about this on Twitter24Share on Google+23
  • Tim Reynolds

    A good read.

    Question: your show function sets the style to inherit. I believe it should be an empty string. By setting it to inherit, you would override the display of a class assigned to the element. I wrote up a gist that shows you what I mean.

    https://gist.github.com/1560533

  • Chris

    Hmm, just in case you haven’t heard, there’s a very popular library that also makes use of the _ global name, much like jQuery makes use of $: Underscore (http://documentcloud.github.com/underscore/). Nice article and happy coding!

  • http://nixtu.blogspot.com Juho Vepsäläinen

    I probably would have written all those functions outside the prototype so I can test them standalone (e is passed as param) and done some magic to bind them later on to bind them there.

    I probably wouldn’t have used prototype either to achieve chaining. Closures do just for fine for my purposes.

    There’s no single right way to write JS, though. It’s amazingly versatile little language. :)

    • admin

      Hey, Juho – Thanks for the feedback. I haven’t seen closures used to achieve chaining before. Mind demonstrating how you would do that (maybe jsfiddle.net or similar)? I agree, JS can be quite the utility-belt.

      • http://oscargodson.com Oscar Godson

        @admin

        For the jQuery like affect, this method is right. You really don’t need the prototype on that tho. You could have laid it out like:

        https://gist.github.com/b508c8234828e6ab55b8

        However, it might be worth noting how to do true JS chain, not a hack to use classes like C++:

        http://jsbin.com/asuhoc

      • http://nixtu.blogspot.com Juho Vepsäläinen

        Hi,

        I set up a simple demo for you. I just took your code and shifted it around bit. The biggest advantage of this approach is that it allows you to use both functional and chaining API.

        I’ll probably evolve this a bit further and write a blog post about it.

        I have written a chaining assert using a similar idea. It’s possible to maintain some state in the chain as you can see from this example (ie. the “not” op).

        If you ever get into Haskell, keep in mind that chaining is analogous to monads. They’ve just packaged it there a bit differently. By default Haskell code doesn’t have any order of execution. Chaining (monads) provide a way to execute things in order around there. In addition they’ll give you a nice way to control side effects.

        • http://oscargodson.com Oscar Godson

          Pretty clever actually passing around an identifier that way. I haven’t written any JS libs that way, but it’s worth checking performance.

          I asked this:
          https://plus.google.com/101249212022203738924/posts/QgL9a1C32cC

          and wrote this test there:
          http://jsbin.com/acojag/2

          I’m curious of the speed of your method? If you get time you should add a test to that with your example.

          • http://nixtu.blogspot.com Juho Vepsäläinen

            It’s effin slow. :S Here’s the modded test, http://jsbin.com/acojag/3 .

            Slicing arguments makes it even worse. I wonder why it’s so snail-like. Is there anything that could be done about it?

            Anyhow it looks like prototypes are the way to go if one wants decent performance.

          • http://nixtu.blogspot.com Juho Vepsäläinen

            I figured out why it was so slow. I forgot to memoize it. :)

            Here’s the corrected version, http://jsbin.com/acojag/4/ . Here on Chrome it’s around seven times faster than the vanilla version. It seems to be faster than class based solution even.

            I think this is a good compromise. It gives me my dual API (both funcs + chaining) and decent performance.

    • http://oscargodson.com Oscar Godson

      I probably wouldn’t have used prototype either to achieve chaining. Closures do just for fine for my purposes.

      Huh? Prototypes contain closures? You can’t even write JS without closures unless you are purely writing a single jQuery line or something.


      a.prototype.b = function(){
      var x = function(y){
      console.log(y)
      }
      return this;
      }

      That contains a closure, so what do you mean? Did you mean classes?

      Also, JavaScript is a prototypal language. Not using prototypal JS is like not using classes in C++.

      • http://nixtu.blogspot.com Juho Vepsäläinen

        Good point! That’s definitely a closure. Some confusion there on my part. I rarely use prototypes myself. I like to dabble with the functional side of JS these days.

        I probably should have rephrased that as “without prototypes”.

  • Nathan

    Probably the best way to deal with the identifier / identifier collision is to provide an override, as jQuery does with jQuery == $

    I think this is worthwhile because people are generally conditioned to using $ at this point.

    As mentioned above, Underscore does a lot of this, but it’s specifically built to not collide with jQuery from a functionality standpoint.

  • Weng

    Could you please provide example for the Visual Basic script please? VB Script is superior to the JavaScript and is made by a well known company. JavaScript is made by volunteers and charity workers.

    • admin

      Lol. Thank you for this great quote. I’ll be sure to give you credit when I post it around.

      -Mike

    • Dan

      Lol. Really? Wow.

    • Ralph

      LOL! This sarcastic comment really made my day! Or? Are you really serious?… Nah!

  • Pingback: My first JavaScript library – short.js « Matt Wein's Global Scope

  • jeefo

    Thank you so much.
    That is actually what i was looking for it.

  • blackhat

    thanks man ,
    that really helped !

  • Chris

    Thanks a lot, this is exactly what I needed. I’m just starting to get familiar with java script for my new job, and this put me on the right track.

  • Jason

    Dude, thank you for such an informative, well-written post. It’s content like this that I really miss seeing on the web these days.
    Side note: I went to click the star button to rate the article, but it changed it to -1. So I tried clicking again to make it go up. Now it says -5. Sorry about that.

  • Billy Stanley

    The purpose of my own library is simply this: 1) I don’t want anything running on my sites that I didn’t write. 2) I don’t want to have to write anything more than once.

    • mdjasper

      Both lovely ideals! Did this article help you in writing your library?

      • http://aleksasavic.com/ Aleksa

        Yes it did help both of us.

  • weirdsteve

    Thanks so much, this is what i really wanted to learn about and with your help I have created an animation lib to make javascript slideshows and games more dynamic.. Thanks again!

    • mdjasper

      Thanks for your comments! Feedback like this motivates me to keep writing. BTW, I’d love a link to your library (if its public).

  • http://www.facebook.com/erick.ribeiro.1042 Erick Ribeiro

    Excelent! I ll make my own.

    • mdjasper

      Good to hear this helped! What will your library do?

  • http://www.facebook.com/panda.biswabhusan Biswabhusan Panda

    Search your Programming problems here http://CodeRND.com

  • Ryanc1256

    Well this article helped a lot, with coding up my own js Library…
    Its Very Simular to Jquery…

    GitHub Link….
    https://github.com/Ryanc1256/Library

  • Rick Yoder

    Don’t know if you’ll answer this before I figure it out, but is there a way to access one function from the library in ANOTHER function of the library?

    My library (thanks for helping me make it), has a .css() method.

    _(“#testing”).css(“display”) would tell me the value of the display property of the element.

    I have another method, .getDimensions().

    I want to return the width and height of the element, using the .css() method.

    How can I do this (if possible)?

    • mdjasper

      Yes, you can call one function from your library from another function using the this keyword. Here is a simple example:

      var library = {
      add: function(a,b){
      return a+b;
      },
      doubleIt: function(a){
      return this.add(a,a);
      }
      };
      library.doubleIt(3); // 6

  • Rick Yoder

    Never mind. Got it.

  • jenya

    can you please give the example how you using your library,i make something like this
    _(“#box”).bgcolor(“yellow”)

    & its not changing anything
    can you contact me by gmail or facebook?

  • jenya

    & how i adding events
    thank you )))))))

  • jenya

    can you please give the example how you using your library,i make something like this
    _(“#box”).bgcolor(“yellow”)

    & its not changing anything
    can you contact me by gmail or facebook?

    & how i adding events
    thank you )))))))

  • tvance929

    Something interesting to note… in VStudio I wasnt able to see the toggle function in the intellisense until after we changed the scope from window to the actual instantiation of the object. Makes perfect sense, just thought it was a cool sidenote.

  • Pingback: Convert Javascript functions into a library [on hold] | BlogoSfera

  • Thiago Facchini

    Nice tutorial… but, what if I want events, such as onMouseOver or something similar?

  • Thiago Facchini

    Thanks for your post very useful.

    Btw: I’ve been looking for a template able to work with: parameters, events and methods.

    Anyone knows a good js template for this purpose? Thanks

  • http://www.facebook.com/people/Landon-Sanders/658858097 Landon Sanders

    Wow!

  • Pingback: JavaScript Module Pattern | BootStrapGo

  • venz

    Thanks a lot for this article. It really helps me!!! I found now what i was looking for

  • Luiz Augusto

    Hey Michael. :)

    I’m using your tutorial to create my own lib and I’d like to know how would you do to create “private” functions (if you needed to)?

  • zhengjunwei

    very good!

  • CodySCarlson

    Hi,

    Great article! I’m familiar with creating modules, libraries, and frameworks — anything from simple functions to modules which include many design patterns. My biggest question now is, if I want to create a framework which contains several dependencies — how to manage this in an elegant way?

    My goal is to have a seamless inclusion of dependencies, but not make the user have to config a path or include the scripts themselves, for ease of use. In addition, I would like to conceal the dependencies to make marketing the framework less difficult (initially anyway).

    Right now I have the minified dependencies pasted into the source file (yuck), which is after approaching it with a document.createElement(‘script’) method. My first priority is to include RSVP.js as virtually everything will rely on Promises — however, I debate if I should first pull in RequireJS to make requests for all other dependencies, and to get the RequireJS config out of the way.

    Should I have a tightly-coupled source file containing the dependencies, where I have to past in newer releases of those dependencies???

    Should I package the dependencies and force the user to include them???

    How is this caveat typically solved?

    Any thoughts on how I can seamlessly load the dependencies and thoughts on approaches is very appreciated.