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:
(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.
(function(){
var div = document.getElementById("mydiv");
var div2 = document.createElement("div");
var h2 = document.createElement("h2");
h2.setAttribute("id", "myHeader");
h2.innerHTML = "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.
(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.
(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.]
Methods added to String.prototype
- trim()
- Returns a new string with whitespaces removed from beginning and end of a string.
Example:
var msg = " Hello ";
var trimmedMsg = msg.trim();
- ltrim()
- Returns a new string with whitespaces removed from beginning of a string.
Example:
var msg = " Hello ";
var trimmedMsg = msg.ltrim();
- rtrim()
- Returns a new string with whitespaces removed from end of a string.
Example:
var msg = " Hello ";
var trimmedMsg = msg.rtrim();
Methods added to the HTMLElement.prototype
- empty()
- Removes all child elements.
Return: Reference to the calling element node.
Example:
node.empty();
- removeSelf() alias rmSelf()
- Removes the element
Example:
node.removeSelf();
- hasClass(string className)
- Determines if the element has a certain class or not.
Return: True/False.
Example:
if(node.hasClass("class1"))
alert("class1 is present");
- 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:
node.removeClass("class1", "class2");
- addClass(string className [,string className])
- Adds one or more CSS class.
Return: Reference to the calling element node.
Example:
node.addClass("class1", "class2");
- 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:
node.toggleClass("class1", "class2");
- addEventHandler(string eventType, function handler)
- Attach an event listener.
Return: Reference to the calling element node.
Example:
node.addEventHandler("click",
function(){alert("Clicked");}).addEventHandler(
"mouseout", function(){alert("Mouse Out");});
- removeEventHandler(string eventType, function handler)
- Detach an event listener.
Return: Reference to the calling element node.
Example:
node.removeEventHandler("click",
clickHandler).removeEventHandler("mouseout", mouseoutHandler);
- setAttributes(obj attributes) alias setAttr(obj attributes)
- Set one or more attributes of the element.
Return: Reference to the calling element node.
Example:
node.setAttributes({
type: "button",
value: "Hello"
});
- setStyles(obj stylesObj)
- Set one or more inline CSS style of the element.
Return: Reference to the calling element node.
Example:
node.setStyles({
color: "blue",
background: "#F55",
"-webkit-transform": "rotate(180deg)",
border: "1px solid black"
});
- 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:
var div = node.appendChildElement("div").addClass("myclass");
div.removeClass("myclass");
- 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:
var div = node.prependElement("div");
- 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:
var textnode = node.appendChildTextNode("Hello World");
var txtnodes = node.appendChildTextNode("Hello\nWorld", true);
- 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:
var textnode = node.prependTextNode("Hello World");
var txtnodes = node.prependTextNode("Hello\nWorld", true);
- 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:
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";
t.nodes.namedTD.innerHTML="Krishna";
- 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:
var o1 = node1.overlay();
var div = document.createElement("div");
div.appendChildTextNode("Hello World");
var o2 = node2.overlay(div);
Global methods
- 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:
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");
- newTextNode(string content) alias newTxtNd(string content)
- Returns a new text node with the specified contents.
Example:
var txt = newTextNode("Hello World");
document.body.appendChild(txt);
- kAlert(string message)
- Uses overlay to show an alert message.
Return: Refrence to the alert element.
Example:
var kA = kAlert("Hello\nWorld");
- kConfirm(string message)
- Uses overlay to show an confirm message.
Return: Refrence to the confirm element.
Example:
var kC = kConfirm("Confirmation required.\nDo you want to proceed?");
- kPrompt(string message, [string/number placeHolder, string/number defaultValue])
- Uses overlay to show an input prompt.
Return: Refrence to the prompt element.
Example:
var kP =
kPrompt("Enter a number.\n(Range: 0 to 100).","Enter number here");
Properties of overlay
- resize()
- Function to resize the overlay when required.
Example:
var o = node.overlay();
o.resize();
- content
- Refrence to the content div in the overlay.
Example:
var o = node.overlay(someContent);
o.content.addClass("mystyleclass");
- replaceContent(obj node)
- Method to replace the content of the overlay.
Example:
var o = node.overlay(someContent);
o.replaceContent(someNewContent);
- appendContent(obj node)
- Method to append more content in the overlay.
Example:
var o = node.overlay(someContent);
o.appendContent(someMoreContent);
- clearContent()
- Method to clear all content from overlay.
Example:
var o = node.overlay(someContent);
o.clearContent();
- destroy()
- Method to remove the overlay.
Example:
var o = node.overlay(someContent);
o.destroy();
Properties of kAlert
- destroy()
- Method to remove kAlert.
Example:
var ka = kAlert("Hello World");
ka.destroy();
- ok
- Refrence to the ok button.
Example:
var ka = kAlert("Hello World");
ka.ok.onclick = ka.destroy;
Properties of kConfirm
- destroy()
- Method to remove kConfirm.
Example:
var kc = kConfirm("Do you want to proceed?");
kc.destroy();
- ok
- Refrence to the ok button.
Example:
var kc = kConfirm("Do you want to proceed?");
kc.ok.onclick = function(){
kc.destroy();
handleTransaction();
}
- cancel
- Reference to the cancel button.
Example:
var kc = kConfirm("Do you want to proceed?");
kc.cancel.onclick = function(){
kc.destroy();
}
Properties of kPrompt
- destroy()
- Method to remove kPrompt.
Example:
var kp = kPrompt("Enter the count","Enter a positive integer");
kp.destroy();
- ok
- Reference to the ok button.
Example:
var kp = kPrompt("Enter a number.");
kp.ok.onclick = function(){
var data=kp.input.value;
kp.destroy();
useData(data);
}
- cancel
- Refrence to the cancel button.
Example:
var kp = kPrompt("Enter a number.");
kp.cancel.onclick = function(){
kp.destroy();
}
- input
- Refrence to the input textbox.
Example:
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