Personal JavaScript library

Share on Facebook
Share on Twitter
Have you ever found yourself in a situation when you needed to perform a fairly simple task (like add a class to an element and then, later on, remove it again) and had to use a huge JavaScript library? Or needlessly deal with naming conventions that do not suite you as you would rather use `toggleDisplay` rather than just `toggle` for instance.
Share on Facebook
Share on Twitter

Why not use existing?

There are countless reasons why using a JavaScript library (even several) is a good idea. To list some of them.

  • it saves time, energy and nerves
  • they are generally well written to be lighting quick
  • they allow you to set up complex functionality with couple of lines of code

That all sounds like a dream. So what's the problem? Well for starters, many libraries are not particularly small in size and loading several of them might already have an impact on the loading speed of your website (which could, affect your *SEO ranking*). Additionally, the functionality might not exactly meet your needs and a custom modification is often a tedious task.

Prior to the ES6 object destructuring, there was a one issue with libraries that stood above all others. Importing a whole set of functions to achieve just couple of simple tasks is an overkill. Greatly enough, there is a simple solution: writing your own small personal JavaScript library filled with custom helper functions. This approach offers a great deal of advantages:

  • you have a full control over the functionality and names of your functions
  • you define only what you need
  • you define exactly what you need
  • you learn something new (the greatest benefit)

1 Motivation

Defining my first function

So how to begin? Well, look at your code a lookup functions that come from external libraries. Choose one that you use often and recreate it yourself. Oftentimes, you need to add a class on a certain event and than remove it again on some other. Let us start with these two.

2 My own functions

addClass(element, className)

In principle, this function is straightforward. Choose an element and assign a desired class name to it. Therefore, this function is going to take two parameters - `element` and `className`. In order to set a class, we're going to use setAttribute() method that takes two parameters. First is an element's attribute we wish to alter - class; the other one is value that will be assigned to the given attribute. So the code looks like this.


function addClass (element, newClass){
  element.setAttribute('class', newClass);
}

This function already works as expected on many occasions. However, it also screws everything up on many more. For instance, it throws an exception when the passed element does not exist, it removes former classes and sets just the new one and also unnecessarily replaces the exact same class if it already exists. The final code, that takes into account all these issues, could look like this.


function addClass (element, newClass){

    // Check if element exists, exit if not
    if (!element){
        return;
    }

    // if the element has no class, just add a new class
    else if (element.getAttribute('class') == null){
        element.setAttribute('class', newClass);
    }

    // if the class already exists, exit
    // you could extract the condition into a stand-alone function (hasClass for instance)
    else if (return new RegExp('(\\s|^)' + className + '(\\s|$)').test(element.getAttribute('class'))){
        return;
    }

    // If the element already has a class, add the new one to the list
    else {
        element.setAttribute('class', element.getAttribute('class') + ' ' + newClass);
    }
}

Even this code is not flawless. For example, in some legacy browsers the setAttribute() and getAttribute() methods don't exist. In that case, this function would throw an error. However, that further highlights the main advantages of this approach - you have the full control. You decide what exceptions and potential issues take into account and which not. If there is an edge case you would like cover, nothing holds you back.

removeClass(element, className)

The logic here is the same really. Take the element, check if the element exists and then remove the desired class. To mix things up, the code does not check whether the class exists as in the previous example. Instead, this function runs a regular expression (RegExp) that matches the given text against a predefined pattern. In practice, it replaces the class list with a new one without the className parameter when it found the class, otherwise it just returns the same class list.


function removeClass (element, className){
    // Check if element exists, exit if not
    if (!element || element.getAttribute('class') === null) {
        return;
    }

    // first get the current class list, get rid of the desired class and return new state
    var newState = element.getAttribute('class').replace(new RegExp('(\\s|^)' + className + '(\\s|$)', 'g'), '$2');

    //set the new class list
    element.setAttribute('class', newState);
}

Conclusion

There you have it, first two functions for your personal JavaScript library. The great advantage is that when something breaks, you know where to look and track down the issue real quick. Clean, flexible and lightweight solution for small projects. Neat.

3 Summing up

< back