Category Archives: DOM

Prototype.js library

Some of my old notes from Prototype (3-4 yrs older so there might be changes)

Overview

Prototype is a JavaScript toolkit. This helps in generation of a application by providing commonly used functionality so that the developer does not have to spend time on them.

The Prototype JS has features provides some basic functions which work as short cuts to already existing functionalities e.g. $() can be used in place of document.getElementById(), there are other complex functions for dealing with XMLHttpRequest. A many other libraries are created by extending this library.

You can download the free prototype.js from http://www.prototypejs.org/download. Once downloaded this JavaScript file can be added to any HTML page just like any other JavaScript file <script type=”text/javascript” src=”prototype.js”></script>

Key Functionalities

Let us look at some of the major functionalities provided by Prototype which makes life of developer simple.

$():

This is equivalent to saying document.getElemetById()
e.g.
var name=$(‘name’);

is same as
var name=document.getElementByID(‘name’);

Where HTML has
<input type= “text” id= “name” value= “John”/>

$$():

This will return you an array of elements from HTML document
e.g.
var eleArray= $$(“#formName input”);

This would return an array of all input type fields inside the form formName. This can be further used like

for(var i=0; i<eleArray.length; i++)
{
valueArray=eleArray[i].value;
}

$F():

To get the value of an element in the page
$F(‘name’) is equivalent to document.getElementByID(‘name’).value;

$A():

$A() Creates an array
var arrayOfNodes= $A(xmldoc.getElementsByTagName(‘abc’));

$H():

$H() Creates a hash table
var employeeHash= $H({
name: “John”,
email: “John@company.com”,
employeeId: “12345”
});

Try.these() Function:

This is an interesting function which lets developer write multiple functions. The code keep trying executing functions until one of them is success. This can be helpful if we are writing code to be supported by multiple versions of JavaScript or multiple browsers

Try.these(
function() {//do something
alert (“first one worked”);
return;
},
function() { // do something
alert (“second one worked”);
return;
}

AJAX Object:

Prototype provides AJAX object to minimize the effort using any AJAX related methods. AJAX object further provides the following classes.

AJAX.Request:

Ajax.Request object encapsulates the commonly used Ajax code for setting up the XMLHttpRequest object, performing cross-browser checking for compatibility and callback handling.

function ajaxFunction() {
var ajaxHandle= new Ajax.Request(
url, {
method: ‘get’,
parameters: { username: ‘Anything’},
onSuccess: process,
onFailure: function() {
alert(“There was an error with the connection”);
}
});
}

AJAX.Updater:

This is similar to the AJAX.Rrquest method above, with an additional feature that it can also update the page with the information returned by server to AJAX call.
new Ajax.Updater(container, url[, options])
function ajaxFunction() {
var ajaxHandle= new Ajax.Request(
‘placeholder’,
url, {
method: ‘get’,
parameters: { username: ‘Anything’},
}
});
}

AJAX.Responders:

AJAX responders are more of global methods which we register and unregister at the start and end of execution of code. They monitor all the AJAX activity going on and show the processing activities (say some animation while the data is being fetched from the server).
Ajax.Responders.register(attributes)
Ajax.Responders.unregister(attributes)
Some of the most common callbacks which are used with responders is
Ajax.Responders.register({
onCreate: showProcessing,
onComplete: hideProcessing
});

Additional Links

http://www.prototypejs.org/
http://www.sergiopereira.com/articles/prototype.js.html
http://attic.scripteka.com/prototype_cheatsheet_1.6.0.2.pdf
http://particletree.com/features/quick-guide-to-prototype/

Object Oriented JavaScript- 4

We have talked about Basic OO concepts, Objects and Classes, and Inheritance in JS. Today, let me look at polymorphism in JS.

Now polymorphism is a criteria which can help me create multiple method with the same name, with the program deciding at the run time, that which method to be called, based on signature of the method. The signature of methods can differ by number of arguments it takes, or type of arguments. In Js, we can not differentiate between methods based on type of arguments, because every type in JS can be treated as type ‘var’. But yes, JS supports polymorphism using different number of arguments, though indirectly.

In a way, polymorphism in JS is simpler than in OO languages. In JS you don’t even need to create multiple methods, in the same method, you can have different handlers for different number of arguments. arguments.length does the trick for you. Enough of talking, here is your example

<script language=”JavaScript”>
//trying to create a closed figure

function closedFigure()
{

this.createFigure=function()
{
var length = arguments.lengt
h;
if(length<3) { alert("atleast 3 sides are required to close the figure"); } if(length==3) { alert("you are trying to create a triangle with "+ arguments[0]+","+arguments[1]+","+arguments[2]); } if(length==4) { alert("you are trying to create a quadrilateral with "+arguments[0]+","+arguments[1]+","+arguments[2]+","+arguments[3]); } if(length==5) { alert("you are trying to create a pentagon with "+arguments[0]+","+arguments[1]+","+arguments[2]+","+arguments[3]+","+arguments[4]); } } } var figure=new closedFigure(); figure.createFigure(1,2); figure.createFigure(1,2,3); figure.createFigure(1,2,3,4); figure.createFigure(1,2,3,3,5); </script>

Object Oriented JavaScript -3

In the last post I talked about how to create objects and classes in JS. The next step is to go for Inheritance.

Continuing from our previous examples, let’s say you want to create a class for rectangle

function rectangle(length, breadth)
{
this.length=length;
this.breadth=breadth;
this.area=setArea;
this.perimeter=setPerimeter;
this.test=function()
{
alert("hi! you are in test function");
}

function setArea()
{
return (this.length*this.breadth);
}

function setPerimeter ()
{
return 2*(this.length+this.breadth);
}
}

let’s save the above code in a file called rectangleScript.js

Now there is a HTML file where you want to use this JS file code. You will simply add

<script type=”text/javascript” src=”rectangleScript.js” language=”javascript”></script>

Next let’s say you want to add some properties and methods to this already existing class. The ‘prototype’ keyword of Java comes into help here.

<script type="text/javascript" src="rectangleScript.js" language="javascript"></script>
<script language="JavaScript">
rectangle.prototype.color="red";
rectangle.prototype.setColor=function(color)
{
this.color=color;
}

rectangle.prototype.isSquare=function()
{
if(this.length==this.breadth)
return true;
else
return false;
}

var rec=new rectangle(2,6);
alert("area here:"+rec.area());
alert("is it a square:"+rec.isSquare());

alert("color:"+rec.color);
rec.setColor("yellow");
alert("color:"+rec.color);

var rec1=new rectangle(3,3);
alert("area here:"+rec1.area());
alert("is it a square:"+rec1.isSquare());
alert("color:"+rec1.color);

</script>

You might still argue that we have not actually inherited a class by another class, this is just adding properties. Yes, even inheriting a class by another is possible in JS. Again prototype keyword is the magic word. Additionally, we will see how method overloading works with JS. Look at this example

<script type="text/javascript" src="rectangleScript.js" language="javascript"></script>

<script language="JavaScript">

function goldenRectangle(length, breadth, someProperty)
//rectangle with length/ breadth=1.618
{
//this.rectangle=new rectangle(length, breadth);

this.length=length;
this.breadth=breadth;
this.newProperty=someProperty;
}

goldenRectangle.prototype =new rectangle();

//Method Overloading

goldenRectangle.prototype.test=function()
{
alert("hi! you are in goldenRectangles test function");
}

var myGoldenRectangle=new goldenRectangle(10,6,1);
alert("area:"+myGoldenRectangle.area());
alert("test property:"+myGoldenRectangle.newProperty);
myGoldenRectangle.test();
</script>

Object Oriented JavaScript -2

Continuing from my first post about this topic, where I mentioned why we need OO JS. First of all let me see what do we picture the moment we say that a language is OO. Here are some basic necessities of OO
Encapsulation: Usage of Classes and Objects
Inheritance: Extending Classes, Overloading methods
Polymorphism: Same method with different number of arguments

Now without wasting further time, lets get on with how these OO principles can be applied to JS

Creating Objects in JS

1. Using Inbuilt Object type:

var myRectangle=new Object();
myRectangle.length=2;
myRectangle.breadth=4;

myRectangle.area=function()
{
return (myRectangle.length*myRectangle.breadth);
}

alert(“area:”+myRectangle.area());

2. The JSON (JavaScript Object Notion) way
var myRectangle2={
length:2,
breadth:4,
area:function()
{
return(this.length*this.breadth);
}
};

alert(“area2:”+myRectangle2.area());

Creating Classes in JS

You might argue that so far we have only created Objects, but in an OO language we first create a class and then create object. Well, that is very much possible in JS as well.

The good news is, that in JS, functions can be treated as classes. How? Let’s check this example.

//Creating a class in JS
function rectangle(length, breadth)
{
this.length=length;
this.breadth=breadth;
this.area=setArea;
this.perimeter=setPerimeter;

this.test=function()
{
alert(“hi! you are in test function”);
}

function setArea()
{
return (this.length*this.breadth);
}

function setPerimeter ()
{
return 2*(this.length+this.breadth);
}
}

var rec=new rectangle(2,6);
var areahere=rec.area();
alert(areahere);
alert(rec.perimeter());

var rec1=new rectangle(1,1);
var areahere=rec1.area();
alert(areahere);
alert(rec1.perimeter());
rec1.test();

More on OO JS (Inheritance and Polymorphism) later

Object Oriented JavaScript

Here are some notes from presentation I have recently given on Object Oriented JS (JavaScript)

Why do we need OO(Object Oriented) JS?

With the popularity of AJAX and similar technologies, role of JS has become relatively more important in Web applications. Earlier you could think of JS just as a facilitator for the actual web application. But now, a lot of coding is being done in JS, sometimes even more than 50% of the code is handled in JS. With more emphasis on usability and look and feel of the application, JS has taken center stage for web applications.

Another reason for JS popularity is because it is easy to code. You don’t need a special training for JS as with other languages like Java. This is because JS was originally meant for designers rather than developers. Now, because it is easy to code, it is easy to mess up too. You don’t have proper structure enforced while coding for JS. That is why need of properly structured OO JS is felt more now.

In addition to above stated reasons, one more concern with JS is that it is highly underused, there are a lot of functionality JS provides you which you don’t use (in many cases we are not even aware of a lot of possibilities JS has)

Traditional Usage of JS
For sake of simplicity, let me take an example where we try to calculate area of rectangle and a square. In traditional usage of JS, we will initially create a JS file and keep adding methods as per our requirements (mostly the JS files ends up in a mess)

Say initially you wanted a method to calculate area of rectangle, you created a method called area, then you wanted to calculate perimeter of teh same rectangle, and you added another method. Sometime later you want to calculate area of square. and so on

<script language=”JavaScript”>

//creating method for calculating rectangle area
function area(length, breadth)
{
return length*breadth;
}

var myArea=area(2,3);
alert(“area is :”+myArea);

//add a method for calculating perimeter
function perimeter(length, breadth)
{
return 2*(length+breadth);
}

var myPerimeter=perimeter(2,3);
alert(“myPerimeter is :”+myPerimeter);

//creating method for calculating square area
function square_area(side)
{
return side*side;
}

var myArea2=square_area(2,3);
alert(“square area is :”+myArea2);
</script>

Now my question is.. is this how we do code in any OO language like Java?

Nope. We will create our classes. We will use polymorphism. We will properly organize our code.

If you are already aware of what I am talking about, you can stop reading. If not, come back tomorrow, I will write more about it.

(..to be continued)

Difference between visibility hidden vs display none

I spent almost an entire day on this, so wanted to share the information in case it might be helpful for others. We at times need to remove a DOM object (textbox/ label/ dropdown etc) from the UI. For which we use two things object.style.visibility=”hidden” and object.style.display=”none”. Though both of them can remove the object from UI, yet there is a significant difference between these two approaches. Whereas visibility hidden will “hide” the object, it will still leave the object on the UI (in hidden format). On the other hand display=”none” will completely remove the object from UI.

The differentiation is more important in a case, where the css being used here does not specify the x and y coordinates for DOM objects, it instead places one object after another. So the trick here is, if I make an object invisible by hiding it (visibility=”hidden”), it will still occupy that one space in the flow, and a blank cell will appear on the screen. Whereas if display is none, then the next object will take place of this object and hence no empty spaces are shown on the screen.

So both the approaches can be used as per ones requirement