Creating your own JavaScript Library

Share on Facebook14Share on Reddit34Tweet about this on TwitterShare on Google+22

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.


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 Reddit34Tweet about this on TwitterShare on Google+22

60 responses to “Creating your own JavaScript Library”

  1. Tim Reynolds says:

    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.

  2. Chris says:

    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 ( Nice article and happy coding!

  3. 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 says:

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

    • Oscar Godson says:

      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){
      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++.

      • 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”.

  4. Nathan says:

    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.

  5. Weng says:

    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.

  6. […] which will be similar to jQuery’s but massively scaled down.  I found a great tutorial here  that walked me through the basics and my end result looks like […]

  7. jeefo says:

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

  8. blackhat says:

    thanks man ,
    that really helped !

  9. Chris says:

    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.

  10. Jason says:

    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.

  11. Billy Stanley says:

    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.

  12. weirdsteve says:

    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 says:

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

  13. Excelent! I ll make my own.

  14. Search your Programming problems here

  15. Ryanc1256 says:

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

    GitHub Link….

  16. Rick Yoder says:

    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 says:

      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

  17. Rick Yoder says:

    Never mind. Got it.

  18. jenya says:

    can you please give the example how you using your library,i make something like this

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

  19. jenya says:

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

  20. jenya says:

    can you please give the example how you using your library,i make something like this

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

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

  21. tvance929 says:

    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.

  22. […] because I just don’t know how to start building a Javascript library. I’ve checked out quite a few articles on how to do it, but all of them do not provide a consistent […]

  23. Thiago Facchini says:

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

  24. Thiago Facchini says:

    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

  25. […] Creating your own JavaScript Library 1 […]

  26. venz says:

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

  27. Luiz Augusto says:

    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)?

  28. zhengjunwei says:

    very good!

  29. CodySCarlson says:


    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.

  30. […] Here are some of my sources: Build Your First JavaScript Library Building a JavaScript Library Creating your own JavaScript Library […]

  31. Mike Morris says:

    You absolutely made me think about what I was doing and how I was blurring the lines between the logic part and the visual part. Angular was too rigid and knockout could not use my lovely TypeLite generated model interfaces directly and drag and drop project management with type safe drop zones and a load of drop placement templates has no business being in the same file as the ajax wrappers.

    That is how my frameworks begin. I think it is like throwing gold in the misc. stack to not record everything you know about programming into namespaced modular frameworks for the languages you use. My classes across PHP and C# include, among hundreds of business specific classes, 2 trivial classes that save me tons of time UspsAddress and GenericDescription. My grail is db table to view with no cast or convert along the way and back. In order to get there everything I learn including the scope matters as it is just beginning to matter to me in the way you are addressing it. My js is scoped to the application first then reaches out to set my event handlers on the document since all html5 DnD events bubble. The reason I did it this way is to avoid the conflict with jq and scope my application object to something like a Bootstrap container wrapping the panel or whatever wrapper..

    You definitely got my wheels turning this day!

  32. M. Paul Peloquin says:

    Thanks for the info. You are awesome. I am using javascript for a

    project. I am comfortable in objective C and swift. I was using jQuery but way to large for what I need to do. You have provided a great solution.

  33. Jhon Ronell Arana says:

    What does the e. ( this.e.) stands for?
    Sorry Noob

  34. Dark Shadow says:

    So, where did the ‘e’ come from in = ‘none’ ? I thought it was just

  35. Dark Shadow says:

    So, where did the ‘e’ come from in = ‘none’ ? I thought it was just

  36. Mark Bauermeister says:

    I know I’m somewhat late to the party, but would you know the proper way to add namespaces to your library framework?
    Basically, I’m attempting to create something like “junior.UI.rainbowBG();” or “junior.App.restart();, junior being the name of my library.

    Furthermore, how should I handle functions that don’t require a target id? A call to my restart function (I’m running the code inside a runtime environment, not just a mere browser. So that function actually restarts the application it’s called from) would currently look like this: “_(‘ ‘).restart();”. Obviously, this isn’t the most elegant looking solution.

  37. tarak M says:

    Hi mdjasper you article is superb.
    I have to create one visualization javascript file on top of d3.
    Plz be give the suggestions.

  38. HongJinBom says:

    Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *