Friday, February 8, 2013

JavaScript HTML DOM Elements (Nodes)

Creating New HTML Elements

To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.

 Example


This is a paragraph.

This is another paragraph.




Try it yourself »


Example Explained 

This code creates a new element:
var para=document.createElement("p");
To add text to the element, you must create a text node first. This code creates a text node:
var node=document.createTextNode("This is a new paragraph.");
Then you must append the text node to the element:
para.appendChild(node);
Finally you must append the new element to an existing element.
This code finds an existing element:
var element=document.getElementById("div1");
This code appends the new element to the existing element:
element.appendChild(para);


Removing Existing HTML Elements

To remove an HTML element, you must know the parent of the element:

Example


This is a paragraph.

This is another paragraph.


Try it yourself »


Example Explained 

This HTML document contains a
element with two child nodes (two elements):

This is a paragraph.

This is another paragraph.

Find the element with id="div1":
var parent=document.getElementById("div1");
Find the element with id="p1":
var child=document.getElementById("p1");
Remove the child from the parent:
parent.removeChild(child);

lamp It would be nice to be able to remove an element without referring to the parent.
But sorry. The DOM needs to know both the element you want to remove, and its parent.
Here is a common workaround: Find the child you want to remove, and use its parentNode property to find the parent:
var child=document.getElementById("p1");
child.parentNode.removeChild(child);


HTML DOM Tutorial

In the HTML DOM section of this JavaScript tutorial you have learned:
  • How to change the content (innerHTML) of HTML elements
  • How to change the style (CSS) of HTML elements
  • How to react to HTML DOM events
  • How to add or delete HTML elements
If you want to learn more about using JavaScript to access the HTML DOM, please go to our
Full HTML DOM Tutorial.

Sunday, February 3, 2013

The Newbie’s Guide to Test-Driven Development

Since the dawn of the computer era, programmers and bugs have battled for supremacy. It’s an inevitable occurrence. Even the greatest programmers fall prey to these anomalies. No code is safe. That’s why we do testing. Programmers, at least sane ones, test their code by running it on development machines to make sure it does what it’s supposed to.

Sane programmer who tests his programs.
Image courtesy of http://www.youthedesigner.com

Insane programmer who doesn’t test his programs.
Image courtesy of http://www.internetannoyanceday.com
Test-driven development is a programming technique that requires you to write actual code and automated test code simultaneously. This ensures that you test your code—and enables you to retest your code quickly and easily, since it’s automated.

How does it work?

Test-driven development, or TDD as we’ll call it from now on, revolves around a short iterative development cycle that goes something like this:
  1. Before writing any code, you must first write an automated test for your code. While writing the automated tests, you must take into account all possible inputs, errors, and outputs. This way, your mind is not clouded by any code that’s already been written.
  2. The first time you run your automated test, the test should fail—indicating that the code is not yet ready.
  3. Afterward, you can begin programming. Since there’s already an automated test, as long as the code fails it, it means that it’s still not ready. The code can be fixed until it passes all assertions.
  4. Once the code passes the test, you can then begin cleaning it up, via refactoring. As long as the code still passes the test, it means that it still works. You no longer have to worry about changes that introduce new bugs.
  5. Start the whole thing over again with some other method or program.

Great, but how is this better than regular testing?

Have you ever purposefully skipped testing a program because:
  • You felt it was a waste of time to test, since it was only a slight code change?
  • You felt lazy testing everything again?
  • You didn’t have enough time to test because the project manager wanted it moved up to production ASAP?
  • You told yourself you’d do it “tomorrow”?
  • You had to choose between manual testing, or watching the latest episode of your favorite TV show (Big Bang Theory)?
Most of the time, nothing happens, and you successfully move your code to production without any problems. But sometimes, after you’ve moved to production, everything goes wrong. You’re stuck fixing a hundred holes in a sinking ship, with more appearing every minute. You do not want to find yourself in this situation.

Screw it, just move it to production!
Image courtesy of http://phenomenaonbreak.wordpress.com
TDD was meant to eliminate our excuses. When a program has been developed using TDD, it allows us to make changes and test quickly and efficiently. All we need to do is run the automated tests, and voila! If it passes all automated tests, then we’re good to go—if not, then it just means we broke something with the changes. By knowing which exact parts of the test failed, it also allows us to easily pinpoint at which part of the changes it broke, so it makes fixing the bugs easier.

I’m Sold. How Do We Do This?

There’s a multitude of PHP automated testing frameworks out there we can use. One of the most widely-used testing frameworks is PHPUnit.
PHPUnit is a great testing framework, which can easily be integrated into your own projects, or other projects built on top of popular PHP frameworks.
For our purposes though, we won’t need the multitude of functions that PHPUnit offers. Instead, we’ll opt to create our tests using a much easier testing framework, called SimpleTest.
In the next steps, let’s assume that we’re developing a guestbook application where any user can add and view guestbook entries. Let’s assume that the markup has been completed, and that we’re simply making a class which contains the application logic of the guestbook, which is where the application inserts and reads to the database. The reading portion of this class is what we’re going to develop and test.

Step 1. Set up SimpleTest

This is arguably the easiest step of all. Even this guy could do it:

I can do this…I can use, my, um…brain!
Image courtesy of http://longstreet.typepad.com/
Download SimpleTest here, and extract to a folder of your choice — preferably the folder where you’re going to develop your code, or your PHP include_path for easy access.
For this tutorial, I’ve set up the folder like so:
Index.php will run guestbook.php, and invoke the view method and display the entries. Inside the classes folder is where we’ll put the guestbook.php class, and the test folder is where we place the simpletest library.

Step 2. Plan Your Attack

The second step, which is actually the most important one, is to start creating your tests. For this, you really need to plan and think about what your function will do, what possible inputs it will get, and the corresponding outputs it will send. This step resembles playing a game of chess—you need to know everything about your opponent (the program), including all his weaknesses (possible errors) and strengths (what happens if it successfully runs).
So for our guestbook application, let’s lay down the schematics:

View

  • This function will not have any inputs since it will just retrieve all of the entries from the database and send back the data to be printed out.
  • It will return an array of guestbook records, stating the name of the poster and his message. If there are no records, then it should still return an empty array.
  • If there are records, the array will have 1 or more values in it.
  • At the same time, the array will have a specific structure, something like:
  1. Array (  
  2.     [0] => Array (  
  3.         ['name'] = "Bob"  
  4.         ['message'] = "Hi, I'm Bob."  
  5.     )  
  6.     [1] => Array (  
  7.         ['name'] = "Tom" 
  8.         ['message'] = "Hi, I'm Tom."  
  9.     )  
  10. )  

Step 3. Write a Test!

Now, we can write our first test. Let’s start by creating a file called guestbook_test.php inside the test folder.
  1. <?php  
  2. require_once(dirname(__FILE__) . '/simpletest/autorun.php');  
  3. require_once('../classes/guestbook.php');  
  4. class TestGuestbook extends UnitTestCase {  
  5. }  
Then, let’s convert what we’ve determined from step two,.
  1. <?php  
  2. require_once(dirname(__FILE__) . '/simpletest/autorun.php');  
  3. require_once('../classes/guestbook.php');  
  4. class TestGuestbook extends UnitTestCase {  
  5.     function testViewGuestbookWithEntries()  
  6.     {  
  7.         $guestbook = new Guestbook();  
  8.         // Add new records first  
  9.         $guestbook->add("Bob""Hi, I'm Bob.");  
  10.         $guestbook->add("Tom""Hi, I'm Tom.");  
  11.         $entries = $guestbook->viewAll();  
  12.         $count_is_greater_than_zero = (count($entries) > 0);  
  13.         $this->assertTrue($count_is_greater_than_zero);  
  14.         $this->assertIsA($entries'array');  
  15.         foreach($entries as $entry) {  
  16.             $this->assertIsA($entry'array');  
  17.             $this->assertTrue(isset($entry['name']));  
  18.             $this->assertTrue(isset($entry['message']));  
  19.         }  
  20.     }  
  21.     function testViewGuestbookWithNoEntries()  
  22.     {  
  23.         $guestbook = new Guestbook();  
  24.         $guestbook->deleteAll(); // Delete all the entries first so we know it's an empty table  
  25.         $entries = $guestbook->viewAll();  
  26.         $this->assertEqual($entriesarray());  
  27.     }  
  28. }  
Assertions make sure that a certain thing is what it’s supposed to be—basically, it ensures that what’s returned is what you’re expecting it to return. For example, if a function is supposed to return true if it’s successful, then in our test, we should assert that the return value is equal to true.

As you can see here, we test the viewing of the guestbook with entries and without. We check if these two scenarios pass our criteria from step two. You probably also noticed that each of our test functions start with the word ‘test.’ We did this because, when SimpleTest runs this class, it will look for all the functions that start with the word ‘test’ and run it.
In our test class, we’ve also used some assertion methods, such as assertTrue, assertIsA, and assertEquals. The assertTrue function checks whether or not a value is true. AssertIsA checks if a variable is of a certain type or class. And lastly, assertEquals checks if a variable is totally equal to a certain value.
There are other assertion methods provided by SimpleTest, which are:
assertTrue($x)Fail if $x is false
assertFalse($x)Fail if $x is true
assertNull($x)Fail if $x is set
assertNotNull($x)Fail if $x not set
assertIsA($x, $t)Fail if $x is not the class or type $t
assertNotA($x, $t)Fail if $x is of the class or type $t
assertEqual($x, $y)Fail if $x == $y is false
assertNotEqual($x, $y)Fail if $x == $y is true
assertWithinMargin($x, $y, $m)Fail if abs($x – $y) < $m is false
assertOutsideMargin($x, $y, $m)Fail if abs($x – $y) < $m is true
assertIdentical($x, $y)Fail if $x == $y is false or a type mismatch
assertNotIdentical($x, $y)Fail if $x == $y is true and types match
assertReference($x, $y)Fail unless $x and $y are the same variable
assertClone($x, $y)Fail unless $x and $y are identical copies
assertPattern($p, $x)Fail unless the regex $p matches $x
assertNoPattern($p, $x)Fail if the regex $p matches $x
expectError($x)Swallows any upcoming matching error
assert($e)Fail on failed expectation object $e
Assertion method list courtesy of http://www.simpletest.org/en/unit_test_documentation.html

Step 4. Fail to Win

Once you’re finished writing the code, you should run the test. The first time you run the test, it SHOULD FAIL. If it doesn’t, then it means that your test doesn’t really test anything.
To run your test, simply run guestbook_test.php in your browser. You should see this first:
This happened because we haven’t created our guestbook class yet. To do so, create guestbook.php inside your classes folder. The class should contain the methods we’re planning to use, but shouldn’t contain anything yet at first. Remember, we’re writing the tests first before writing any code.
  1. <?php  
  2. class Guestbook  
  3. {  
  4.     public function viewAll() {  
  5.     }  
  6.     public function add( $name$message ) {  
  7.     }  
  8.     public function deleteAll() {  
  9.     }  
  10. }  
When you run the test again, it should look something like this:
As we can see here, our test is now winning by failing. This means that our test is now ready to get “answered.”

Step 5. Answer Your Test by Writing Code


At some point, we’ve all felt like this when we’re programming.
Image courtesy of http://fermentation.typepad.com/fermentation
Now that we have a working automated test, we can start writing code. Open up your guestbook.php class and start creating the answer to your test.
  1. <?php  
  2. class Guestbook  
  3. {  
  4.     // To save time, instead of creating and connecting to a database, we're going to  
  5.     // simulate a "database" by creating a static entries array here.  
  6.     // It will be like we have two entries in the table.  
  7.     private static $_entries = array(  
  8.         array (  
  9.             'name' => 'Kirk', 
  10.             'message' => 'Hi, I\'m Kirk.'  
  11.         ),  
  12.         array (  
  13.             'name' => 'Ted',  
  14.             'message' => 'Hi, I\'m Ted.'  
  15.         )  
  16.     );  
  17.     public function viewAll() {  
  18.         // Here, we should retrieve all the records from the database.  
  19.         // This is simulated by returning the $_entries array  
  20.         return self::$_entries;  
  21.     }  
  22.     public function add( $name$message ) {  
  23.         // Here, we simulate insertion into the database by adding a new record into the $_entries array  
  24.         // This is the correct way to do it: self::$_entries[] = array('name' => $name, 'message' => $message );  
  25.         self::$_entries[] = array('notname' => $name'notmessage' => $message ); //oops, there's a bug here somewhere  
  26.         return true;  
  27.     }  
  28.     public function deleteAll() {  
  29.         // We just set the $_entries array to simulate  
  30.         self::$_entries = array();  
  31.         return true;  
  32.     }  
  33. }  
This guestbook.php class has some bugs in it on purpose, so we can see what it looks like if our test fails.
Once we run our test, we should see something like this:
The test output shows us in which test and in which assertion our code failed. From this, we can easily pinpoint that line 16 and 17 was the assertion that threw the error.
  1. <?php  
  2. require_once(dirname(__FILE__) . '/simpletest/autorun.php');  
  3. require_once('../classes/guestbook.php');  
  4. class TestGuestbook extends UnitTestCase {  
  5. ...  
  6. ...  
  7. ...  
  8.     $this->assertTrue(isset($entry['name']));  
  9.     $this->assertTrue(isset($entry['message']));  
  10. ...  
  11. ...  
  12. ...  
  13. }  
This clearly tells us that the returned entry array did not have the correct array key. Based on this, we’ll easily know which part of our code went wrong.
  1. <?php  
  2. class Guestbook  
  3. {  
  4. ...  
  5. ...  
  6. ...  
  7.     public function add( $name$message ) {  
  8.         // Here, we simulate insertion into the database by adding a new record into the $_entries array  
  9.         self::$_entries[] = array('name' => $name'message' => $message ); //fixed!  
  10.         return true;  
  11.     }  
  12. ...  
  13. ...  
  14. ...  
  15. }  
Now, when we run our test again, it should show us:

Step 6. Refactor and Refine Your Code

Since the code we’re testing here is pretty simple, our testing and bug fixing didn’t last very long. But if this was a more complex application, you’d have to make multiple changes to your code, make it cleaner so it’s easier to maintain, and a lot of other things. The problem with this, though, is that change usually introduces additional bugs. This is where our automated test comes in—once we make changes, we can simply run the test again. If it still passes, then it means we didn’t break anything. If it fails, we know that we made a mistake. It also informs us where the problem is, and, hopefully, how we’ll be able to fix it.

Step 7. Rinse and Repeat

Eventually, when your program requires new functionality, you’ll need to write new tests. That’s easy! Rinse and repeat the procedures from step two (since your SimpleTest files should already be set up), and start the cycle all over again.

Conclusion

There are a lot more in-depth test-driven development articles out there, and even more functionality to SimpleTest than what was displayed in this article—things like mock objects, stubs, which make it easier to create tests. If you’d like to read more, Wikipedia’s test-driven development page should set you on the right path. If you’re keen on using SimpleTest as your testing framework, browse the online documentation and be sure to review its other features.
Testing is an integral part of the development cycle, however, it’s too often the first thing to be cut when deadlines are imminent. Hopefully, after reading this article, you’ll appreciate how helpful it is to invest in test-driven development.
What are your thoughts on Test-Driven Development? Is it something you’re interested in implementing, or do you think it’s a waste of time? Let me know in the comments!

The Basics of Object-Oriented JavaScript


Over recent years, JavaScript has increasingly gained popularity, partly due to libraries that are developed to make JavaScript apps/effects easier to create for those who may not have fully grasped the core language yet.
While in the past it was a common argument that JavaScript was a basic language and was very ‘slap dash’ with no real foundation; this is no longer the case, especially with the introduction of high scale web applications and ‘adaptations’ such as JSON (JavaScript Object Notation).

JavaScript can have all that an Object-Orientated language has to offer, albeit with some extra effort outside of the scope of this article.

Let’s Create an Object

  1. function myObject(){  
  2. };  
Congratulations, you just created an object. There are two ways to
create a JavaScript object: they are ‘Constructor functions’ and
‘Literal notation’. The one above is a Constructor function,
I’ll explain what the difference is shortly, but before I do, here
is what an Object definition looks like using literal notation.
  1. var myObject = {  
  2. };  
Literal is a preferred option for name spacing so that your JavaScript
code doesn’t interfere (or vice versa) with other scripts running on the
page and also if you are using this object as a single object and not requiring
more than one instance of the object, whereas Constructor function type
notation is preferred if you need to do some initial work before the object
is created or require multiple instances of the object where each instance
can be changed during the lifetime of the script. Let’s continue to build
on both our objects simultaneously so we can observe what the differences are.

Defining Methods and Properties

Constructor version:

  1. function myObject(){  
  2.     this.iAm = 'an object';  
  3.     this.whatAmI = function(){  
  4.         alert('I am ' + this.iAm);  
  5.     };  
  6. };  

Literal version:

  1. var myObject = {  
  2.     iAm : 'an object',  
  3.     whatAmI : function(){  
  4.         alert('I am ' + this.iAm);  
  5.     }  
  6. }  
For each of the objects we have created a property ‘iAm’ which contains a
string value that is used in our objects method ‘whatAmI’ which alerts a message.
Properties are variables created inside an object and methods are functions created inside an object.
Now is probably as good a time as any to explain how to use properties and
methods (although you would already have done so if you are familiar with a library).
To use a property first you type what object it belongs to – so in this case it’s myObject –
and then to reference its internal properties, you put a full stop and then the name of the
property so it will eventually look like myObject.iAm (this will return ‘an object’).
For methods, it is the same except to execute the method, as with any function, you must
put parenthesis after it; otherwise you will just be returning a reference to the function
and not what the function actually returns. So it will look like myObject.whatAmI()
(this will alert ‘I am an object’).

Now for the differences:

  • The constructor object has its properties and methods defined with the
    keyword ‘this’ in front of it, whereas the literal version does not.
  • In the constructor object the properties/methods have their ‘values’
    defined after an equal sign ‘=’ whereas in the literal version, they are
    defined after a colon ‘:’.
  • The constructor function can have (optional) semi-colons ‘;’ at the
    end of each property/method declaration whereas in the literal version
    if you have more than one property or method, they MUST be separated with
    a comma ‘,’, and they CANNOT have semi-colons after them, otherwise JavaScript will return an error.
There is also a difference between the way these two types of object declarations are used.
To use a literally notated object, you simply use it by referencing its variable name,
so wherever it is required you call it by typing;
  1. myObject.whatAmI();  
With constructor functions you need to instantiate (create a new instance of)
the object first; you do this by typing;
  1. var myNewObject = new myObject();  
  2. myNewObject.whatAmI();  

Using a Constructor Function.

Let’s use our previous constructor function and build upon it so it performs some basic
(but dynamic) operations when we instantiate it.
  1. function myObject(){  
  2.     this.iAm = 'an object';  
  3.     this.whatAmI = function(){  
  4.         alert('I am ' + this.iAm);  
  5.     };  
  6. };  
Just like any JavaScript function, we can use arguments with our constructor function;
  1. function myObject(what){  
  2.     this.iAm = what;  
  3.     this.whatAmI = function(language){  
  4.         alert('I am ' + this.iAm + ' of the ' + language + ' language');  
  5.     };  
  6. };  
Now let’s instantiate our object and call its whatAmI method, filling in the required
fields as we do so.
  1. var myNewObject = new myObject('an object');  
  2. myNewObject.whatAmI('JavaScript');  
This will alert ‘I am an object of the JavaScript language.’

To Instantiate or not to Instantiate

I mentioned earlier about the differences between Object Constructors and Object Literals and that
when a change is made to an Object Literal it affects that object across the entire script, whereas when
a Constructor function is instantiated and then a change is made to that instance, it won’t affect any
other instances of that object. Let’s try an example;
First we will create an Object literal;
  1. var myObjectLiteral = {  
  2.     myProperty : 'this is a property'  
  3.    }  
  4.    //alert current myProperty  
  5.    alert(myObjectLiteral.myProperty); //this will alert 'this is a property'  
  6.    //change myProperty  
  7.    myObjectLiteral.myProperty = 'this is a new property';  
  8.    //alert current myProperty  
  9.    alert(myObjectLiteral.myProperty); //this will alert 'this is a new property', as expected  
Even if you create a new variable and point it towards the object, it will have the same effect.
  1. var myObjectLiteral = {  
  2.     myProperty : 'this is a property'  
  3.    }  
  4.    //alert current myProperty  
  5.    alert(myObjectLiteral.myProperty); //this will alert 'this is a property'  
  6.    //define new variable with object as value  
  7.    var sameObject = myObjectLiteral;  
  8.    //change myProperty  
  9.    myObjectLiteral.myProperty = 'this is a new property';  
  10.    //alert current myProperty  
  11.    alert(sameObject.myProperty); //this will still alert 'this is a new property'  
Now let’s try a similar exercise with a Constructor function.
  1. //this is one other way of creating a Constructor function  
  2. var myObjectConstructor = function(){  
  3.     this.myProperty = 'this is a property'  
  4.    }  
  5.    //instantiate our Constructor  
  6.    var constructorOne = new myObjectConstructor();  
  7.    //instantiate a second instance of our Constructor  
  8.    var constructorTwo = new myObjectConstructor();  
  9.    //alert current myProperty of constructorOne instance  
  10.    alert(constructorOne.myProperty); //this will alert 'this is a property'  
  11.     //alert current myProperty of constructorTwo instance  
  12.    alert(constructorTwo.myProperty); //this will alert 'this is a property'  
So as expected, both return the correct value, but let’s change the myProperty for one of the instances.
  1. //this is one other way of creating a Constructor function  
  2. var myObjectConstructor = function(){  
  3.     this.myProperty = 'this is a property'  
  4.    }  
  5.    //instantiate our Constructor  
  6.    var constructorOne = new myObjectConstructor();  
  7.    //change myProperty of the first instance  
  8.    constructorOne.myProperty = 'this is a new property';  
  9.    //instantiate a second instance of our Constructor  
  10.    var constructorTwo = new myObjectConstructor();  
  11.    //alert current myProperty of constructorOne instance  
  12.    alert(constructorOne.myProperty); //this will alert 'this is a new property'  
  13.     //alert current myProperty of constructorTwo instance  
  14.    alert(constructorTwo.myProperty); //this will still alert 'this is a property'  
As you can see from this example, even though we changed the property of constructorOne
it didn’t affect myObjectConstructor and therefore didn’t affect constructorTwo. Even if
constructorTwo was instantiated before we changed the myProperty property of constructorOne,
it would still not affect the myProperty property of constructorTwo as it is a completely different
instance of the object within JavaScript’s memory.
So which one should you use? Well it depends on the situation, if you only need one object of its kind for
your script (as you will see in our example at the end of this article), then use an object literal, but if you need several instances of an object, where each instance
is independent of the other and can have different properties or methods depending on the way it’s constructed, then use a constructor function.

This and That

While explaining constructor functions, there were a lot of ‘this’ keywords being thrown around
and I figure what better time to talk about scope!
Now you might be asking ‘what is this scope you speak of’?’ Scope in JavaScript is function/object based, so that means if you’re outside
of a function, you can’t use a variable that is defined inside a function (unless you use a closure).
There is however a scope chain, which means that a function inside another function can access a
variable defined in its parent function. Let’s take a look at some example code.
  1. <script type="text/javascript">  
  2. var var1 = 'this is global and is available to everyone';  
  3. function function1(){  
  4.     var var2 = 'this is only available inside function1 and function2';  
  5.     function function2(){  
  6.         var var3 = 'this is only available inside function2';  
  7.     }  
  8. }  
  9. </script>  
As you can see in this example, var1 is defined in the global object
and is available to all functions and object, var2 is defined inside function1
and is available to function1 and function2, but if you try to reference it from the global object
it will give you the error ‘var2 is undefined’, var3 is only accessible to function2.

So what does ‘this’ reference? Well in a browser, ‘this’ references the window object, so technically
the window is our global object. If we’re inside an object, ‘this’ will refer to the object itself however
if you’re inside a function, this will still refer to the window object and likewise if you’re inside a method
that is within an object, ‘this’ will refer to the object.
Due to our scope chain, if we’re inside a sub-object (an object inside an object), ‘this’ will refer to
the sub-object and not the parent object.
As a side note, it’s also worth adding that when using functions like setInterval, setTimeout and eval,
when you execute a function or method via one of these, ‘this’ refers to the window object as these are methods of window, so
setInterval() and window.setInterval() are the same.
Ok now that we have that out of the way, let’s do a real world example and create a
form validation object!

Real world Usage: A Form Validation Object

First I must introduce you to the addEvent function which we will create and is a
combination of ECMAScript’s (Firefox, Safari, etc.. ) addEventListener() function and
Microsoft ActiveX Script’s attachEvent() function.
  1. function addEvent(to, type, fn){  
  2.     if(document.addEventListener){  
  3.         to.addEventListener(type, fn, false);  
  4.     } else if(document.attachEvent){  
  5.         to.attachEvent('on'+type, fn);  
  6.     } else {  
  7.         to['on'+type] = fn;  
  8.     }  
  9. };  
This creates a new function with three arguments, to being the DOM object we are attaching
the event to, type being the type of event and fn being the function run when
the event is triggered. It first checks whether addEventListener is supported, if so it will use that, if not it will check
for attachEvent and if all else fails you are probably using IE5 or something equally obsolete so
we will add the event directly onto its event property (note: the third option will overwrite any
existing function that may have been attached to the event property while the first two will add
it as an additional function to its event property).
Now let’s set up our document so it is similar to what you might see when you develop jQuery stuff.
In jQuery you would have;
  1. $(document).ready(function(){  
  2.     //all our code that runs after the page is ready goes here  
  3. });  
Using our addEvent function we have;
  1.    addEvent(window, 'load'function(){  
  2.     //all our code that runs after the page is ready goes here  
  3. });  
Now for our Form object.
  1. var Form = {  
  2.     validClass : 'valid',  
  3.     fname : {  
  4.         minLength : 1,  
  5.         maxLength : 15,  
  6.         fieldName : 'First Name'  
  7.     },  
  8.     lname : {  
  9.         minLength : 1,  
  10.         maxLength : 25,  
  11.         fieldName : 'Last Name'  
  12.     },  
  13.     validateLength : function(formEl, type){  
  14.         if(formEl.value.length > type.maxLength || formEl.value.length < type.minLength ){  
  15.             formEl.className = formEl.className.replace(' '+Form.validClass, '');  
  16.             return false;  
  17.         } else {  
  18.             if(formEl.className.indexOf(' '+Form.validClass) == -1)  
  19.             formEl.className += ' '+Form.validClass;  
  20.             return true;  
  21.         }  
  22.     },  
  23.     validateEmail : function(formEl){  
  24.         var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;  
  25.         var emailTest = regEx.test(formEl.value);  
  26.         if (emailTest) {  
  27.             if(formEl.className.indexOf(' '+Form.validClass) == -1)  
  28.             formEl.className += ' '+Form.validClass;  
  29.             return true;  
  30.         } else {  
  31.             formEl.className = formEl.className.replace(' '+Form.validClass, '');  
  32.             return false;  
  33.         }  
  34.     },  
  35.     getSubmit : function(formID){  
  36.         var inputs = document.getElementById(formID).getElementsByTagName('input');  
  37.         for(var i = 0; i < inputs.length; i++){  
  38.             if(inputs[i].type == 'submit'){  
  39.                 return inputs[i];  
  40.             }  
  41.         }  
  42.         return false;  
  43.     }  
  44. };  
So this is quite basic but can easily be expanded upon.
To break this down first we create a new property which is just the string name of our 'valid' css class
that when applied to the form field, adds valid effects such as a green border. We also define our two sub-objects, fname and lname,
so we can define their own properties that can be used by methods elsewhere, these properties are minLength
which is the minimum amount of characters these fields can have, maxLength which is the max characters
the field can have and fieldName which doesn't actually get used, but could be grabbed for
things like identifying the field with a user friendly string in an error message (eg. 'First Name field is required.').
Next we create a validateLength method that accepts two arguments: formEl the DOM element to validate
and the type which refers to one of the sub-object to use (i.e. fname or lname).
This function checks whether the length of the field is between the minLength and maxLength range, if it's not
then we remove our valid class (if it exists) from the element and return false, otherwise if it is then we add the valid class and return true.
Then we have a validateEmail method which accepts a DOM element as an arguement, we then test this DOM elements value against an
email type regular expression; again if it passes we add our class and return true and vice versa.
Finally we have a getSubmit method. This method is given the id of the form and then loops through all input elements inside the specified form
to find which one has a type of submit (type="submit"). The reason for this method is to return the submit button so we can
disable it until the form is ready to submit.
Let's put this validator object to work on a real form. First we need our HTML.
  1. <body>  
  2. <form id="ourForm">  
  3.     <label>First Name</label><input type="text" /><br />  
  4.     <label>Last Name</label><input type="text" /><br />  
  5.     <label>Email</label><input type="text" /><br />  
  6.     <input type="submit" value="submit" />  
  7. </form>  
  8. </body>  
Now let's access these input objects using JavaScript and validate them when the form submits.
  1. addEvent(window, 'load'function(){  
  2.     var ourForm = document.getElementById('ourForm');  
  3.     var submit_button = Form.getSubmit('ourForm');  
  4.     submit_button.disabled = 'disabled';  
  5.     function checkForm(){  
  6.         var inputs = ourForm.getElementsByTagName('input');  
  7.         if(Form.validateLength(inputs[0], Form.fname)){  
  8.             if(Form.validateLength(inputs[1], Form.lname)){  
  9.                 if(Form.validateEmail(inputs[2])){  
  10.                         submit_button.disabled = false;  
  11.                         return true;  
  12.                 }  
  13.             }  
  14.         }  
  15.         submit_button.disabled = 'disabled';  
  16.         return false;  
  17.     };  
  18.     checkForm();  
  19.     addEvent(ourForm, 'keyup', checkForm);  
  20.     addEvent(ourForm, 'submit', checkForm);  
  21. });  
Let's break down this code.
We wrap our code in the addEvent function so when the window is loaded this script runs.
Firstly we grab our form using its ID and put it in a variable named ourForm, then we grab
our submit button (using our Form objects getSubmit method) and put it in a variable named submit_button,
and then set the submit buttons disabled attribute to 'disabled'.
Next we define a checkForm function. This stores all the inputs inside the form field as an array and we attach it to a
variable named.. you guessed it.. inputs!
Then it defines some nested if statements which test each of the fields inside the inputs array against our Form methods.
This is the reason we returned true or false in our methods, so if it returns true, we pass that if statement and continue onto the next,
but if it returns false, we exit the if statements.
Following our function definition, we execute the checkForm function when the page initially loads and also attach the function to a keyup event
and a submit event.
You might be asking, why attach to submit if we disabled the submit button. Well if you are focused on an input field and hit the enter key, it will
attempt to submit the form and we need to test for this, hence the reason our checkForm function returns true (submits the form) or false (doesn't submit form).

Conclusion

So we learned how to define the different object types within JavaScript and create properties and methods within them. We also learned a nifty addEvent function and got to use our object in a basic real world example.
This concludes the basics of JavaScript Object Orientation. Hopefully, this may start you on your way to building your own JavaScript library! If you liked this article and are interested in other JavaScript related topics, post them in the comments as I'd be happy to continue writing them. Thanks for reading.