Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

kLib: Fast, Small, and Easy

4.96/5 (7 votes)
12 Jun 2013CPOL7 min read 28.5K   374  
kLib: A small library to make DOM operations very easy.

kLib: What and Why    

{
Edit: New version added (v1.1.0)
Major highlights:
  • All the overlay related functions are seperated form the main library. Now only the DOM manipulation functions are in the main library. The overlay functions have been added to a new sub-library called kLib-Overlay.
  • New functions to for adding sibling elements, textnodes and element trees.
  • Major internal code refactoring, resulting in smaller file size.
  • Increased efficiency in many of the functions.
Link to kLib-CSS article
Link to kAlert(), kConfirm(), kPrompt() demo.
}

Everyone who has ever had a chance to work on client side of an web application has had to deal with dynamic creation/modification of HTML elements. Generally people create new elements tree in javascript as follows:

JavaScript
(function(){
    document.getElementById("mydiv").innerHTML = 
      '<h2 id="myHeader"> My Header </h2> ' + 
      '<div class="blueBorder"> <p> ' + 
      '<span>Hello World</span> </p> </div>';
    document.getElementById("myHeader").
             firstChild.nextSibling.firstChild.firstChild.onclick=function(){
        alert("Span Clicked");
    }
})(); 

Although javascript provides native functions for creating elements, I have found that people are reluctant in using it. (Perhaps because it increases the size of the code.) I for one always use the javascript's functions for creating elements, primarily because it returns a refrence to the element node which can then be used directly for further operations (like adding event handler). This method also allows me change the elements position in the element tree without modifying any related code.

JavaScript
(function(){
    var div = document.getElementById("mydiv");
    var div2 = document.createElement("div");
    var h2 = document.createElement("h2");
    h2.setAttribute("id", "myHeader");
    h2.innerHTML = "My Header"
    // or h2.appendChild(document.createTextNode("My Header"));

    var p = document.createElement("p");
    var span  = document.createElement("span");
    span.innerHTML = "Hello World";
    p.appendChild(span);
    div2.appendChild(p);
    div2.className = "blueBorder";
    div.appendChild(h2);
    div.appendChild(div2);
    span.onclick = function(){
        alert("Span Clicked");
    }
})();

The second code achieved the same result but the code was a little longer. But it gave me direct access to the span element to add an event handler. If there is a lot of this kind of operations (which is usually the case) then the second approach makes much sense, because we will not need to parse the DOM tree for the intended element.

I wanted to get the best of both worlds i.e. small code as well as easy access and direct control.
Towards this goal I started writing kLib. The first alpha versions allowed me to achieve the following result.

JavaScript
(function(){
    var div = document.getElementById("mydiv");
    div.addChElem("h2").setAttr(
           {id:"myHeader"}).innerHTML="My Header";
    var span= div.addChElem("div").addClass(
      "blueBorder").addChElem("p").addChElem("span");
    span.innerHTML="Hello World";
    span.onclick = function(){
        alert("Span Clicked");
    }
})();

This reduced the a code a little bit. After further development the current version of kLib offers.

JavaScript
(function(){
    var tree = document.getElementById("mydiv").addChElemTree(
      ["hRef=h2#myHeader", "div.blueBorder", 
      ["p", ["sRef=span"]]]);
    tree.nodes.hRef.innerHTML = "My Header";
    tree.nodes.sRef.innerHTML = "Hello World";
    tree.nodes.sRef.onclick = function(){
        alert("Span Clicked");
    }
})();

This method allows me to create the whole element tree (of any size) in just one line. kLib contains many such functions to make your life easier.

Apart from the DOM manipulation functions kLib has set of functions to create overlays [like the overlayed facebook photo viewer] over any visible HTML element (including the body). The overlay creation is very flexible and can be used to create virtually any kind of overlay.
In addition to the general overlay function, kLib includes overlayed (non-blocking) alternatives to the alert, confirm, and prompt function.

This is a work in progress. I intend to work on it whenever I have free time.
Following is the list of functions provided by kLib. I have tested them in Chrome (Win and Android), Firefox (Win and Android), Opera Mobile (Android) and IE10.
If you find any bug or have any ideas to improve the code please feel free to contact me via email.
Do you find it useful? Please let me know in the comments.


Brief Descriptions of kLib Functions/Properties

Version: 1.0.4 

[Edit: There were some spelling mistakes in the codes. I have corrected all of them which ever I could find. I have attached a new Doc file with the same corrections.]

  1. Methods added to String.prototype

    1. trim()
      Returns a new string with whitespaces removed from beginning and end of a string.
      Example:
      JavaScript
      var msg = "  Hello  ";
      var trimmedMsg = msg.trim();//This makes trimmedMsg="Hello"
    2. ltrim()
      Returns a new string with whitespaces removed from beginning of a string.
      Example:
      JavaScript
      var msg = "  Hello  ";
      var trimmedMsg = msg.ltrim();//This makes trimmedMsg="Hello   "
    3. rtrim()
      Returns a new string with whitespaces removed from end of a string.
      Example:
      JavaScript
      var msg = "  Hello  ";
      var trimmedMsg = msg.rtrim();//This makes trimmedMsg="   Hello"
  2. Methods added to the HTMLElement.prototype 

    1. empty()
      Removes all child elements.
      Return: Reference to the calling element node.
      Example:
      JavaScript
      node.empty();
    2. removeSelf()   alias   rmSelf()
      Removes the element
      Example:
      JavaScript
      node.removeSelf();
    3. hasClass(string className)
      Determines if the element has a certain class or not.
      Return: True/False.
      Example:
      JavaScript
      if(node.hasClass("class1"))
      alert("class1 is present");
    4. removeClass(string className [,string className])   alias   rmClass(string className [,string className])
      Removes one or more CSS class.
      Return: Reference to the calling element node.
      Example:
      JavaScript
      node.removeClass("class1", "class2");
    5. addClass(string className [,string className])
      Adds one or more CSS class.
      Return: Reference to the calling element node.
      Example:
      JavaScript
      node.addClass("class1", "class2");
    6. toggleClass(string className [,string className])
      Toggles one or more CSS class (i.e. if class is present then it is removed and if class is not present then it is added).
      Return: Reference to the calling element node.
      Example:
      JavaScript
      node.toggleClass("class1", "class2");
    7. addEventHandler(string eventType, function handler)
      Attach an event listener.
      Return: Reference to the calling element node.
      Example:
      JavaScript
      node.addEventHandler("click", 
        function(){alert("Clicked");}).addEventHandler(
        "mouseout", function(){alert("Mouse Out");});
    8. removeEventHandler(string eventType, function handler)
      Detach an event listener.
      Return: Reference to the calling element node.
      Example:
      JavaScript
      node.removeEventHandler("click", 
        clickHandler).removeEventHandler("mouseout", mouseoutHandler);
    9. setAttributes(obj attributes)   alias   setAttr(obj attributes)
      Set one or more attributes of the element.
      Return: Reference to the calling element node.
      Example:
      JavaScript
      node.setAttributes({
      	type: "button",
      	value: "Hello"
      });
    10. setStyles(obj stylesObj)
      Set one or more inline CSS style of the element.
      Return: Reference to the calling element node.
      Example:
      JavaScript
      node.setStyles({
      	color: "blue",
      	background: "#F55",
      	"-webkit-transform": "rotate(180deg)",
      	border: "1px solid black"
      });
    11. appendChildElement(string tagName)   alias   addChElem(string tagName)
      Append a child element of the specified type.
      Return: Reference to the child element.
      Parameter tagName can be of the same format as specified for newElement(). //newElement() is defined in the Global Methods section
      Example:
      JavaScript
      var div = node.appendChildElement("div").addClass("myclass");
      div.removeClass("myclass");
    12. prependElement(string tagName)   alias   prependElem(string tagName)
      Add a child element of the specified type in the parent of current element just before the current element.
      Return: Refrence to the child element.
      Parameter tagName can be of the same format as specified for newElement(). //newElement() is defined in the Global Methods section
      Example:
      JavaScript
      var div = node.prependElement("div");
    13. appendChildTextNode(string content [, bool multiline])   alias   addChTxtNd(string content [, bool multiline])
      Append a child text node and add the specified content to it.
      Return: Refrence to the child text node. (When multiline is true then it returns an array containing refrences to all the text nodes)
      Example:
      JavaScript
      var textnode = node.appendChildTextNode("Hello World");
      var txtnodes = node.appendChildTextNode("Hello\nWorld", true);
    14. prependTextNode(string content [, bool multiline])   alias   prependTxtNd(string content [, bool multiline])
      Add a child text node with the specified content in the parent element of the current element just before the current element.
      Return: Refrence to the child text node. (When multiline is true then it returns an array containing refrences to all the text nodes)
      Example:
      JavaScript
      var textnode = node.prependTextNode("Hello World");
      var txtnodes = node.prependTextNode("Hello\nWorld", true);
    15. appendChildElementTree(obj treeObj [, bool makeDumpString)]   alias   addChElemTree(obj treeObj [, bool makeDumpString)]
      It takes element node-tree data via a specially designed array and then appends the tree to the calling node.
      Return: A tree (as array) containing all the nodes (format is same as it was at the time of passing).
      When true is passed in place of makeDumpString then the return array has a special property called dumpStr which can be used to easily identify the array index of any specific node.
      The tag names can be of the same format as specified for newElement(). //newElement() is defined in the Global Methods section.
      User can also provide property names to create ana alias for any elements index in the tree.
      This will allow the user to directly access any element if he so desires.
      If nomes are provided then the refrence property is generated inside the nodes property of the tree.
      Example:
      JavaScript
      var t = document.body.addChElemTree(["table#maintable", 
        ["tr", ["td", "td"]], 
        ["tr.blue", ["td", "namedTD=td"]]], true);
      console.log(t.dumpStr);
      t[1][1][0].innerHTML="Hello";
      t[1][1][1].innerHTML="World";
      t[2][1][0].innerHTML="Anshu";
      t[2][1][1].innerHTML="Krishna";
      //Since a name was provided for the index [2][1][1] therefore
      // t[2][1][1] is same as t.nodes.namedTD. So this line can also be written as
      t.nodes.namedTD.innerHTML="Krishna";
    16. overlay([obj node])
      Add a child div with class "klib-overlay-main-div". Then set this div to act as an overlay over self (i.e. this element). Add a container div with class "klib-overlay-container-div". Then add the specified node as a child inside the container div.
      Also place the container in the center of overlay.
      Return: Refrence to the calling element node.
      Example:
      JavaScript
      var o1 = node1.overlay(); //Blank Overlay
      
      var div = document.createElement("div");
      div.appendChildTextNode("Hello World");
      var o2 = node2.overlay(div); //Overlay with content node.
  3. Global methods

    1. newElement(string tagName)   alias   newElem(string tagName)
      Returns a new HTMLElement object of the specified tag type.
      The parameter tagName can be formatted to add id or CSS class to the element as well.
      Like:
      For {div, id="maindiv"} tagName = "div#maindiv"
      For {div, class="bluediv"} tagName = "div.bluediv"
      For {div, id="maindiv", class="bluediv"} tagName = "div#maindiv .bluediv"

      Example:
      JavaScript
      var div = newElement("div");
      document.body.appendChild(div);
      
      var div = newElement("div#maindiv");
      var div = newElement("div.bluediv");
      var div = newElement("div#maindiv .bluediv");
      var div = newElement("div.bluediv bolddiv");
      var div = newElement("div#maindiv .bluediv bolddiv");
    2. newTextNode(string content)   alias   newTxtNd(string content)
      Returns a new text node with the specified contents.
      Example:
      JavaScript
      var txt = newTextNode("Hello World");
      document.body.appendChild(txt);
    3. kAlert(string message)
      Uses overlay to show an alert message.
      Return: Refrence to the alert element.
      Example:
      JavaScript
      var kA = kAlert("Hello\nWorld");
    4. kConfirm(string message)
      Uses overlay to show an confirm message.
      Return: Refrence to the confirm element.
      Example:
      JavaScript
      var kC = kConfirm("Confirmation required.\nDo you want to proceed?");
    5. kPrompt(string message, [string/number placeHolder, string/number defaultValue])
      Uses overlay to show an input prompt.
      Return: Refrence to the prompt element.
      Example:
      JavaScript
      var kP = 
        kPrompt("Enter a number.\n(Range: 0 to 100).","Enter number here");
  4. Properties of overlay

    1. resize()
      Function to resize the overlay when required.
      Example:
      JavaScript
      var o = node.overlay();
      /*
      * Some code which resizes node
      */
      o.resize(); 
    2. content
      Refrence to the content div in the overlay.
      Example:
      JavaScript
      var o = node.overlay(someContent);
      o.content.addClass("mystyleclass");
    3. replaceContent(obj node)
      Method to replace the content of the overlay.
      Example:
      JavaScript
      var o = node.overlay(someContent);
      o.replaceContent(someNewContent);
    4. appendContent(obj node)
      Method to append more content in the overlay.
      Example:
      JavaScript
      var o = node.overlay(someContent);
      o.appendContent(someMoreContent);
    5. clearContent()
      Method to clear all content from overlay.
      Example:
      JavaScript
      var o = node.overlay(someContent);
      o.clearContent();
    6. destroy()
      Method to remove the overlay.
      Example:
      JavaScript
      var o = node.overlay(someContent);
      o.destroy();
  5. Properties of kAlert

    1. destroy()
      Method to remove kAlert.
      Example:
      JavaScript
      var ka = kAlert("Hello World");
      ka.destroy();
    2. ok
      Refrence to the ok button.
      Example:
      JavaScript
      var ka = kAlert("Hello World");
      ka.ok.onclick = ka.destroy;
      //Note: This onclick is set by default too.
      //You do not need to set this everytime you use kAlert.
  6. Properties of kConfirm

    1. destroy()
      Method to remove kConfirm.
      Example:
      JavaScript
      var kc = kConfirm("Do you want to proceed?");
      kc.destroy();
    2. ok
      Refrence to the ok button.
      Example:
      JavaScript
      var kc = kConfirm("Do you want to proceed?");
      kc.ok.onclick = function(){
      	kc.destroy();
      	handleTransaction();
      }
    3. cancel
      Reference to the cancel button.
      Example:
      JavaScript
      var kc = kConfirm("Do you want to proceed?");
      kc.cancel.onclick = function(){
      	kc.destroy();
      }
  7. Properties of kPrompt

    1. destroy()
      Method to remove kPrompt.
      Example:
      JavaScript
      var kp = kPrompt("Enter the count","Enter a positive integer");
      kp.destroy();
    2. ok
      Reference to the ok button.
      Example:
      JavaScript
      var kp = kPrompt("Enter a number.");
      kp.ok.onclick = function(){
      	var data=kp.input.value;
      	kp.destroy();
      	useData(data);
      }
    3. cancel
      Refrence to the cancel button.
      Example:
      JavaScript
      var kp = kPrompt("Enter a number.");
      kp.cancel.onclick = function(){
      	kp.destroy();
      }
    4. input
      Refrence to the input textbox.
      Example:
      JavaScript
      var kp = kPrompt("Enter a number.");
      kp.ok.onclick = function(){
      	var data=kp.input.value;
      	kp.destroy();
      	useData(data);
      }
Library written by: Anshu Krishna
Contact: anshu.krishna5@gmail.com

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)