How to Easily Create a JavaScript Framework, Part 1
May 20th, 2009 by TweetCurrently, JavaScript is the one of the most utilized and popular programming language, because a large majority of the browsers are compatible with it and make use of it. Therefore, JavaScript has become very popular, very fast, because it is so uncomplicated, straightforward, and has a wide-range of capabilities. Nearly all programmers used to think that JavaScript was a toy language, but the emergence of AJAX into the market manifested something completely to the contrary, because it showed JavaScript diverse capabilities and functionalities. Since this discovery, programmers can create web applications that give the impression of desk top application, which is helpful because data can be changed more quickly.
However, the use of DOM in the browsers, such as Internet Explorer, makes it difficult to work with JavaScript at times. Consequently, that is why JavaScript frameworks are now exploding onto the market, in order to make cross browser scripting possible. Popular JavaScript frameworks like Prototype, JQuery, YUI, and Dojo have been used for the last five years by many programmers around the world to create amazing web applications. Now, I am going to take you step by step to create a JavaScript framework, walking through the DOM simple effects and AJAX utilities. Hopefully, you can take this information and learn to implement it yourself.
What is on topic for today?
- Avoiding Global Variables
- Creating a Main Object/Framework
- DOM Navigation Part 1
- Chaining Methods
1. Avoiding Global Variables
Before we start creating the VOZ framework, we should know that we have to avoid global variables in all pages because JavaScript uses the last variable declaration with its value without warning that we declared it in a sentence before. For example:
var x = 23; //Declare and use the x variable assigning 23 as value;
var x = 44; //Assign 44 to the variable without warning that our variable is already declared
x; //The actual value is 44
A good method to avoid global variables is creating a anonymous function that keeps our variable inside the function scope. For example:
(function(){
//Variables and functions go here.
})();
Anonymous functions are very useful when we are working with JavaScript Frameworks, because we can pass them as value to our functions. We will see that later.
2. Creating a Main Object/Framework
It is well known that JavaScript has two ways to create objects: Constructor Functions and Literal Objects.
Constructor functions:
//Defining the Object/Class User with two parameters “name and lastname”.
function User(name, lastname){
this.name = name;
this.lastName = lastname;
}
//To use the User Object/Class with new
var myUser = new User('Carl','Anderson');
myUser.name // It returns “Carl”
Literal Object:
The second way and the most recommended by experts like Douglas Crockford is the Literal Object. This style is what we are going to use to create our Framework, because it is the most elegant and efficient way to create objects. For example:
myUser = {
name: 'Carl',
lastName: 'Anderson'
};
myUser.name //Returns “Carl”
Well, enough with theories, let’s put this into action and create our Framework. First, select a short, attractive name for your framework. For this example, I will use the name “VOZ.” For example:
// Wrapping my framework to avoid unpredictable errors with others frameworks and variables.
(function (){
//Creating our framework named VOZ
var VOZ = {}
})();
Now we have our framework ready but we need to create some a property and some methods. For now we are going to add “getById,” “addClass,” and “ON” methods.
(function(){
var VOZ = {
//The elems array is going to contains all the elements in order to chain
elems :[],
//The method to get Elements By Id
getById:function(){},
//Method to add a CSS Class
addClass:function(){},
//Method to add an event to our Elements
on:function(){},
//Add text into an element
appendText:function(){}
//Show/Hide
toggleHide:function(){}
}
})() ;
Literal Object:
3. DOM Navigation Part 1
Walking trough the DOM is vital for a Javascript programmer, because that gives you the ability to modify, delete, or add new elements in an specific place of the web page.
The method for now is “getById;” however, this is not the normal “document.getElementById” method, because this takes more than one parameter to find the elements by their ID. For example:
//Get all elements by Id
//It could take more than one parameter
getById:function(){
var tempElems = []; //temp Array to save the elements found
for(var i = 0; i < arguments.length;i++){
if(typeof arguments[i] === 'string'){ //Verify if the parameter is an string
tempElems.push(document.getElementById(arguments[i])); //Add the element to tempElems
}
}
this.elems = tempElems; //All the elements are copied to the property named elems
return this; //Return this in order to chain
},
We have a method to find elements by ID, but let’s create the next method that adds a class name to our elements, called “addClass”:
//Add a new class to the elements
//This does not delete the all class, it just add a new one
addClass:function(name){
for(var i = 0;i < this.elems.length;i++){
this.elems[i].className += ' ' + name; //Here is where we add the new class
}
return this; //Return this in order to chain
},
The last method for today is "ON," that is used to add events in our elements, e.g. 'click', 'mouseover','mouseout', etc.
//Add an Event to the elements found by the methods: getById and getByClass
//--Action is the event type like 'click','mouseover','mouseout',etc
//--Callback is the function to run when the event is triggered
on: function(action, callback){
if(this.elems[0].addEventListener){
for(var i = 0; i < this.elems.length;i++){
this.elems[i].addEventListener(action,callback,false);//Adding the event by the W3C for Firefox, Safari, Opera...
}
}
else if(this.elems[0].attachEvent){
for(var i = 0; i < this.elems.length;i++){
this.elems[i].attachEvent('on'+action,callback);//Adding the event to Internet Explorer
}
}
return this;//Return this in order to chain
},
To attach text into our elements, we can use this method:
//Append Text into the elements
//Text is the string to insert
appendText:function(text){
text = document.createTextNode(text); //Create a new Text Node with the string supplied
for(var i = 0; i < this.elems.length;i++){
this.elems[i].appendChild(text);//Append the text into the element
}
return this;//Return this in order to chain
},
To show/hide the elements found, we use this method:
//Show and Hide the elements found
toggleHide:function(){
for(var i = 0; i < this.elems.length;i++){
this.elems[i].style['display'] = (this.elems[i].style['display']==='none' || '') ?'block':'none'; //Check the status of the element to know if it could be displayed or hided
}
return this;//Return this in order to chain
}
Lastly, let's add this at the end of the object:
if(!window.$$){window.$$=VOZ;}//We create a shortcut for our framework, we can call the methods by $$.method();
This is to use our framework with the $$ like shortcut. For example:
$$.getById('myElement')
Now our framework looks like this:
(function(){
var VOZ = {
elems:[],//Array to save all the elements found by the functions getById, getByC
//Get all elements by Id
//It could take more than one parameter
getById:function(){
var tempElems = []; //temp Array to save the elements found
for(var i = 0;i < arguments.length;i++){
if(typeof arguments[i] === 'string'){ //Verify if the parameter is an string
tempElems.push(document.getElementById(arguments[i])); //Add the element to tempElems
}
}
this.elems = tempElems; //All the elements are copied to the property named elems
return this; //Return this in order to chain
},
//Add a new class to the elements
//This does not delete the all class, it just add a new one
addClass:function(name){
for(var i = 0; i < this.elems.length;i++){
this.elems[i].className += ' ' + name; //Here is where we add the new class
}
return this; //Return this in order to chain
},
//Add an Event to the elements found by the methods: getById and getByClass
//--Action is the event type like 'click','mouseover','mouseout',etc
//--Callback is the function to run when the event is triggered
on: function(action, callback){
if(this.elems[0].addEventListener){
for(var i = 0; i < this.elems.length;i++){
this.elems[i].addEventListener(action,callback,false);//Adding the event by the W3C for Firefox, Safari, Opera...
}
}
else if(this.elems[0].attachEvent){
for(var i = 0;i < this.elems.length;i++){
this.elems[i].attachEvent('on'+action,callback);//Adding the event to Internet Explorer
}
}
return this;//Return this in order to chain
},
//Append Text into the elements
//Text is the string to insert
appendText:function(text){
text = document.createTextNode(text); //Create a new Text Node with the string supplied
for(var i = 0; i < this.elems.length;i++){
this.elems[i].appendChild(text);//Append the text into the element
}
return this;//Return this in order to chain
},
//Show and Hide the elements found
toggleHide:function(){
for(var i = 0; i < this.elems.length;i++){
this.elems[i].style['display'] = (this.elems[i].style['display']==='none' || '') ?'block':'none'; //Check the status of the element to know if it could be displayed or hided
}
return this;//Return this in order to chain
}
}
if(!window.$$){window.$$=VOZ;}//We create a shortcut for our framework, we can call the methods by $$.method();
})();
4. Chaining
Chaining is the ability to call methods together. This makes your code more understandable and organized.
Without Chaining
$('#element').method1();
$('#element').method2();
$('#element').method3();
With Chaining
$('#element').method1().method2().method3();
VOZ JavaScript Framework Example
Please visit the above link in order to view the first part of our VOZ framework put into action! Also, stay tuned for the second part of this post, which is in the works! I hope you enjoyed reading this tutorial and found it easy to follow! Please feel free to comment, as I love to hear from fellow developers!
Pass your 70-649 in first attempt using 000-106 dumps and other resources. We offer 100% success in real exam with up to date pmp dumps, 350-030 braindumps, and 70-640 dumps.
Teylor Feliz is a well-known XHTML/CSS/JavaScript enthusiast from Dominican Republic. He has more than 10 years experience in the computer programming, graphic design, and web development world, including 2 years teaching computer science. Teylor has a degree in Applied Sciences from the University of Louisiana and is completing a Master’s degree in IT with a concentration in Web Design and Development, at the University of Denver.
Subscribe to our RSS
Please help us to promote this article.







very very cool & good article, thank you very much for sharing.
When you complete this framework, can you share it on my JavaScript site, http://javascriptbank.com/submit/ ?
Thank
great tutorial thank you..
Thanks everyone for the comments! Stay tuned for Part 2 in the next week or so!
grt artical …thanks…
i been lurking all around the web top found tutorial on how to create javascript framework..thank god i found ur site
its easily foloow and understandable..keep up a good work
Great! I am glad you found the tutorial useful! I will be coming out with parts three and four soon! Keep checking back! Thanks.
sure i keep checking this site daily to know if there is any update on this tutorial..big thanks bro
in ur example page,i see u intilize the whole libarray using window.onload event..is this a good approach?
can u achive something like jQuery read() method?
$(document).ready(function(){
//do stuff
})
i think the code for initilize ur library should not be in window.onload function
cause ur libarary is self invoking function and then register the VOZ object to global $$ variable
correct me if im wrong
view-source:http://admixweb.com/downloads/vozframework/vozpart1.html
Yes, you are 100% right, but I want people not to care about the window.onload before we talk about the domReady function. I just put all the code inside of the window.onload = function(){..code here..} because it looks less complicated. Does that explain your question?
Yes u did
i just want to clarify that cause i myself not very familiar with javscript since im come from php background
thanks to you now i have learn so many thing in javascript
so is there any news about part 3 and part 4 ??
cant wait on it
Stay tuned! We should post it this week.
Thanks for your interest!
Good to hear that…
Thanks admin
yes part 2, 3, 4 soon please
punctilious post. simply one detail where I contest with it. I am emailing you in detail.
Great tutorial! Thanks!
Greate job!
Great tutorial ! ! !
Is part II to be expected?
Hey Khan, the tutorials are already posted through the site. I will make a new post with all of them together.
Thanks for your comment!
Very interesting! Thanks!!!
But I cannot understand 1 thing:
Your example works. But If to delete 1 button (id=”myButton” ), other _independent_ button (id=”myButtonToggle”) doesn’t operate.
As I see (after some experiments w/ the code), the beginnings of these IDs should be the same (otherwise Hide btn doesn’t work). Might there be an error in getById?
Hi,
I’m a bit late since this post is now “old”, but this is a great tutorial to show people the power and elegance of Javascript
I’m not sure, but I think there’s a problem with the toggleHide() function. I’m not sure I understand the following line:
this.elems[i].style['display'] = (this.elems[i].style['display']===’none’ || ”) ?’block’:'none’;
Whenever an element is hidden, and has to be shown, it will always be shown as a “block” (in CSS terminology).
But users may want to hide and show “inline” elements such as images, I guess. With this function, I think it will not work as it should (images will behave as “block” elements as soon as they are shown again).
My CSS/Javascript skills are a bit rusty, but I think that if you set the display property to “” (empty string), then it is implicitly set to the default display style of the element you’re working on. That is, “block” for a div, “inline” for an img, and so on.
Also, how does the condition work? Why is it ( … === ‘none’ || ” ) ?
Thanks
You are right in both, it is very old and it is true about the display property.
It should be:
I was using the ternary operators which is just a short IF … ELSE
This just check if the style is ‘none’ it would assign an empty string to the ‘display’ property (which reset the visibility to a previous or normal status that could be inline or block), and if the condition is false it would assign ‘none’ to the element property.
If you have any question just let me know.
Thank you for your comment!
Really nice article. Keep up the good work.