Referring to an element in HTML page

How to select an element in an HTML page? This is often get in my way, while beginning to learn Javascript, CSS and HTML. The simple answer is with javascript we have a method named “getElementById()” and always works as

document.getElementById('element ID');

Lets dive into code and see how things work. Lets say we have an HTML page as



	


		
		
		
	
	
		
Hello World.
Hello you, this is JS.

There are two “div” tags in it and they are having id values as “one” and “two” respectively. Then we have two buttons inside the second “div”. These buttons are having id values as “btnOne” and “btnTwo”. Why we are adding id values?! Well, these are basics of how to access items from inside a page. Its kind of naming a new born in family :) Lets move on and see how we are accessing these elements.
Our javascript file looks as below

var onPageLoad = function ()
{
	 alert("Page is loaded");
	 var myBtnOne = document.getElementById('btnOne');
	 var myBtnTwo = document.getElementById('btnTwo');
	 //alert(myBtnOne+' : '+myBtnTwo);
	 
	 myBtnOne.onclick=function(){
	 	alert ('one');
	 };
	 
	 myBtnTwo.onclick=function(){
	 	alert ('two');
	 };
	 
};

Before going into the javascript, lets see our HTML code again. There is something, we did not look previously. Its

	

What this does ?!! To be very basic, it actually calls a javascript function named “onPageLoad()” , when all the elements on the HTMl page is loaded. That means, we can add any interactivity after the page is loaded. For, if we try to add interactivity before all elements of the page is loaded, then there is a chance javascript engine will ignore those commands which will result in wrong behavior of the page. Therefore its recommended to add functionality to a page after confirming that everything in the page is loaded and this code is exactly doing the same.
Coming to out javascript file, we have to written everything in our “onPageLoad()” function. So the first thing is taken care of, now lets move on and see what else we are doing. Upon page loaded it will “alert” a message to the user saying we are ready to start adding interactivity. Now our main ambition here is to upon clicking those two buttons, we have to alert different messages to the user. We select those button elements with the code

document.getElementById('btnOne');

Next, we have to store these values so as to refer them in our code. We do this by assigning them to a variable as

var myBtnOne = document.getElementById('btnOne');

For the second button we have to do the same thing and the code looks

 var myBtnOne = document.getElementById('btnOne');
 var myBtnTwo = document.getElementById('btnTwo');

Now we know how to access elements from an HTML page. The process is add an id value to the element in HTML page and access them with “document.getElementById(elementName)”. Thats all.
Next we are simply going to add the interactivity. Those are done with

 myBtnOne.onclick=function(){
	 	alert ('one');
	 };
myBtnTwo.onclick=function(){
	 	alert ('two');
	 };

Thats simple, but then there are libraries which make our job even simpler. JQuery is such a library, but that is for a future post.
All the sourceCode can be downloaded from here for your reference.

Hope that helps some one. I would like to listen back from you about the post, leave a comment for suggestions, mistakes or simply thanks.

javascript : prototype and __proto__

Note that __proto__ is a property of the instances, whereas prototype is a property of their constructor functions. Ref : Mozilla Developer Network
With that it may seem that we have another property, which we can use. But the reality is “__proto__” is a custom implementation and only available toGecko Javascript engines, which is used in Firefox.
A lot advice to use this only to study the “prototype” chain of javascript but not use it in any practical application. Here is a nice explanation about the two.
Now even, Mozilla is deprecating the “__proto__” and instead suggests to use “Object.getPrototypeOf”. Here John Resig explains the new property.

Hope that helps.

javascript : Inheritence by prototype

Once we got the basic information and know how, of the “prototype” property of a constructor object, we need some code to test it. So here is another all in one page test for the “prototype” property.
We have 3 constructors and then the prototype property of the constructors are defined as another object. Basically, if 3 constructors namely A,B,C are present, prototype of A is defined as an object created by “new B()”, prototype of B is defined as an object created by “new C()”. There are 4 different properties in all the objects. But the relationship is now as below

A.prototype is new B(); 
B.prototype is new C()
//so the relation is as below
A -> B -> C

That means, “prototype” allows us to make a relation between the objects. We will see that in a moment. Now all the properties of all the objects can be accessed through the object created by “new A()”.
If you have not yet opened the all in one page test for this example, open it now. And click the buttons to see the properties accessed from one Object.

var ClassA=(function(){
	//------define-------
	var a,b,c,d,getA,getB,getC,getD,numberToBeAdded;
	//------configure------
	a='Property a';
	b=500;
	c='Property c';
	d='Property d';
	//numberToBeAdded=100;//prototype object can not access this property, instead the local property will be used
	this.numberToBeAdded=100;//With the use of "this" now its exposed to be accesed from its prototype object
	//------expose-------
	this.getA=function(){
		return a;
	}
	this.getB=function(){
		return b;
	}
	this.getC=function(){
		return c;
	}
	this.getD=function(){
		return d;
	}
	//
	/*
	this.getSum=function(userNumber){
		return userNumber+numberToBeAdded;
	}
	*/
});
//
var ClassB=(function(){
	//------define-------
	var e,f,g,h,getE,getF,getG,getH;
	//------configure------
	e='Property e';
	f=9;
	g='Property g';
	h='Property h';
	//numberToBeAdded=200;
	//------expose-------
	this.getE=function(){
		return e;
	}
	this.getF=function(){
		return f;
	}
	this.getG=function(){
		return g;
	}
	this.getH=function(){
		return h;
	}
	//
	/*
	this.getSum=function(userNumber){
		return userNumber+numberToBeAdded;
	}
	*/
});
//
var ClassC=(function(){
	//------define-------
	var i,j,k,l,getI,getJ,getK,getL,getSum,numberToBeAdded;
	//------configure------
	i='Property i';
	j=300;
	k='Property k';
	l='Property l';
	numberToBeAdded=300;//"this" exposes this number to be overriden by the object which will prototype ClassC(or this class)
	//------expose-------
	this.getI=function(){
		return i;
	}
	this.getJ=function(){
		return j;
	}
	this.getK=function(){
		return k;
	}
	this.getL=function(){
		return l;
	}
	//
	this.getSum=function(userNumber){
		//return userNumber+numberToBeAdded;
		return userNumber+this.numberToBeAdded;//using "this" will override the local property and use the property of the object which would be using this object as a prototype
	}
});

The code to use the prototype is defined as

//makes the object
var objC=new ClassC();
//makes the prototype magic
ClassB.prototype=objC;
ClassB.constructor=ClassB;
//makes the object
var objB=new ClassB();
//objB.constructor.prototype=objC;
//makes the prototype magic
ClassA.prototype=objB;
ClassA.constructor=ClassA;
var objA=new ClassA();

So how it works?!! This magic is simply possible by “prototype”. For example, if we are trying to access one property in an object created by “new A()” and the property is not present in the Object, then javascript engine will look for the property in the “prototype” object of “new A()” and that in our case is an object created by “new B()” and if the property is not found in it, it will search in the prototype property object defined for this object, that is in our case is an object created by “new C()”.

The code below shows, how we are accessing properties from the prototype object through the single object.

//calling own method
objA.getA();
//calling B's method
objA.getE();
//calling C's method
objA.getJ();

If you go through the code here, you must see that there is the use of the key word “this”. This is simply kind of saying that this property is accessible from outside. In Java or Actionscript kind of languages, its known as “public” variables. Remember that, whatever variables need to be exposed to outside, must be defined with the keyword “this”. Going through the code again will show you that, some properties are just defined with “var”, while some other are defined with “this”. Remember, “this” always points to the current object.

Now with these knowledge, we can very well override or reassign values to our objects, which are defined in the prototype object. That means, if some properties are defined in our “prototype” object and they are exposed or public variables, then we can again define the same variables in our Object and our object variables will be used for calculations. This is very interesting and sometimes get some time to understand too. Again, coming back to code, we have a function in our “prototype” object which adds some numeric value to another given number. Both the actual object and “prototype” object have got the value, which needs to be added. But if the prototype value is exposed with “this” then only the value inside function, which calls this variable with “this” will take actual value from the object not the value from the prototype! Thats because, “this” always refers to the current object.

Here is the source code for this example.

Hope that helps someone. Would love to listen comments, suggestions and insights, as I am still learning it.

javascript : prototype

Moving on with my study of javascript, the next thing is “prototype”. Before that, lets say it three times, “Everything in javascript is an Object“.

There are only 3 primitive datatypes in javascript! Though some refer as, there are 5 types, but all in all those are the only ones. These primitive data types are

string
numeric
boolean
//The other two are
null
undefined

Apart from these basic datatypes, everything else is an Object. Though there are predefined Objects in javascript with these primitive datatype names such as String,Number,Boolean,Null,Undefined respectively. Please refer this for a detailed understanding.
Well, the point here is everything is an Object in Javascript. Unlike other programming languages where a Class is needed to create an Object, Javascript comes with Objects from the beginning. The dynamic nature of the language allows us to do so many things in so many ways that there really needs an eye who can see the details, of how things are done.
We know from past tutorial that “prototype” is a property of an Object created with “new” keyword. What does this do? Well, this allows us to link Objects internally!! Lets take a pause and understand another very important lesson of javascript and object oriented programming in general.
In a Class based language(Java or Actionscript) it is thought as, “how to relate the Classes, so that something is possible?”, where in a dynamic language such as javascript, it is thought as “how to relate the Objects, so that something is possible?” Read it for a number of times so that you will get a hang of the metaphor and thought process difference, in mind.
So the point here is the same, we have to relate the Objects itself but not the Classes(Anyway, we do not have classes here in javascript but can fake them though).
Coming back to our “prototype”, its the property of an Object created through the use of “new”. This “prototype” property is also an Object in itself. To test this, let us refer our previous post, and the all in one page test. Go down to the “Understanding Javascript class.” box and click on the “what is prototype” button. The pop-up will say, its an Object. That’s good, lets move on and click on “prototype test” button, now it alerts “undefined” that means, “prototype” is an object but not yet defined! So lets define a prototype and call the same method again. First to assign an object to the “prototype” property click on “initiate with custom prototype” button. That will assign a custom object as the “prototype” property. Now click on the “prototype test” button again, and this time it will alert with some value, other than “undefined”.
Whoa!! Its that simple. Yes it is that simple and for the same reason many confuse with the concept. After all the world has become complicated to understand simple things :) :)

The source code of the example is here to download.
Happy coding.

javascript : Constructor

The confusion between a “function” and a “constructor” is always there. They may seem very similar from outside, but its the implementation that defines the difference. Actually its not even the function definition which is confusing, but its the concept and dynamism of the language itself.
First important thing to remember is everything in Javascript is an Object.
So anything that is Object can be functional. Now there are two ways we can create objects in javascript.
The basic and most used is the object literal with curly braces as

var myObj={
a:12,
b:"another string",
c:function(){}
};

Now if we want to access any thing of this object, the calls will go as below

myObj.a;
myObj.c();

That was quite straight forward for we are accessing an “object itself”.
Now lets see how we can create objects in another way.

var AnObject=function(){
this.a='A String value';
this.b=12345;
this.c=function(){};
this.d='Another String';
};

The above code is kind of a Class, that means it is not a class by any formal definition, but it is kind of a thing which makes objects. If one tries to access anything from it directly as

AnObject.a;
AnObject.c();

It will simply not work!! Why?! For its not an Object yet. To make an object out of it, we have to use “new” and then call it with a “()” like

var anO=new AnObject();
//now call the properties and methods as below
anO.a;
anO.c();

Thats simply because when we call this kind of object, or create objects in this kind with a “new” and a “()”, its called constructor.

varv anO=new AnObject();

Now this function call with a “new” is known as a constructor.
Apart from this difference there is a huge difference in terms of using “prototype” object of the constructor. The “prototype” itself is a huge topic, so its not explained here. The important thing here is to remember that any object which is created with a constructor has a “prototype” property but the objects, which are created with any other methods do not possess the “prototype” object.

javascript : Making a Library

This is kind of looking at javascript from a fresh perspective. It does not assume you to know anything about it. Knowing another scripting language is always an advantage to know things better but sometimes it may come to a negative effect. If you know anything before, its better to assume you do not know that :) so that we can get up to speed in javascript as quickly as possible.
I hope you have a basic understanding of how to include external javascript and css files inside an HTML document. If not, then please go ahead and follow the posts mentioned below for a quick understanding.
Introduction to HTML
Getting used to the terms
Getting into web design action

Lets setup our experiment with the files listed below

index.html
general.css
saumyaJS.js
general.js

Now, the code inside index file is as below



	


		
		
		
		
		
	
	
		
Hello World.
Hello you, this is JS.

Here we are clearly adding all the CSS and JS files into it. The “general.js” file is where we are going to write the experiment codes. The “saumyaJS.js” is kind of a library we are going to write so as to know the javascript basics and help the experiment. The first line of javascript library includes the JQuery library, if you are not sure about it now, do not worry, just remember that I have used it to select HTML elements from my index.html file. And the JQuery library itself is a huge project,so we will get to that in a future post may be.

I am suggesting to go ahead and read Keith’s blog for getting the hang of javascript environment from a learner’s perspective. He has done a splendid job of putting his 31 days continuous blogpost about javascript.
31 days of Canvas tutorials
March is JavaScript Month. And… Introducing WireLibJS

First and the most important thing is variables in javascript. They are by default “Global”, that means if we define a variable as

a="name";
b=2;
c="message";

Then all these variables are global variables by default. That will allow anyone to access these variables from anywhere. Well, to make local variables we have to define them with “var” keyword. So the definition will go as

var a="name";
var b=2;
var c="message";

Well as you can already guess that there is no restriction in datatype for a variable. And the scope of these local variables are inside a function. In short javascript variables have function level scope. Now lets define a function and add some local variables into it,

myFunction=function(){
	var d=0;
	var firstName='saumya';
	counter = 1;
	
	alert('reset');
};

That means anywhere we need to call this function, we have to call it as below

myFunction();

Thats simple as we define a function with name “myFunction” and invoked it with “myFunction()”. Thats how a function is called.
Now one thing to understand and know is, its better to add as little as possible in global scope. Its a best practice and saves a ton of headache later in the development process. Now in our previous example, we are adding the variable “myFunction” in the global scope. But the variables “d” and “firstName” are in local scope. But then the variable “counter” is in global scope!! Thats the scary part of it. Yeah, anything without a “var” keyword is exposed to Global scope.
The previous example showed how to make a function with a name. It is possible to make a function without a name also, those are called anonymous functions. And since we know, to call a function we have to use “()” at the end of a function, the code below describes how to define an anonymous function and call it.

//makes anonymous function
function()
{
	//Code for function
};
//make the anonymous function and call it at the same time
function()
{
	//Code for function
}();//look at the "()" at the end of the function definition

The problem here is, once the function is called and executed, everything inside the function along with the function itself is not accessible any more. In order to get a reference to the function itself, we need to store it with some name. Thats where the named function comes into picture, that we have seen already as to how to define a named function.
Next we want to make an anonymous function, call it and then save the returned value of the function. A function can return value by using a “return” keyword. Example of a function which returns a value is as below

var myFunction=function(){
return 5;
}();

Now we have a variable named “myFunction” with a value of 5. This is simple but as you can imagine this return type can be anything. The code below shows how to return an “Object”.

var myFunction=function(){
return {one:'fistName',two:'lastName'};
}();

Now “myFunction” simply contains an object with properties “one” and “two”. If we want to access these properties, the call would be as below

myFunction.one;
myFunction.two;

With these knowledge we can write something like below,

var saumyaJS=(function(){
	// --------------- Define -----------------------
	var a,b,c,d,e;//define properties and methods
	// --------------- Configure --------------------
	a='saumya';
	b='ray';
	c=function(msg){
		d++;
		alert(d+':'+msg);
	};
	d=0;
	e=function(){
		d=0;
		alert('reset');
	};
	// --------------- Expose -------------------------
	return {
		firstName:a,
		lastName:b,
		show:c,
		reset:e
		};//expose the properties and methods to outer world
}());

Here simply some local variables are defined, then configured them with values and finally whatever needs to be exposed to outside world, is retuned.
Whoaa!!! We have simply written a simple Javascript library.
If you look into the code a little bit, then its visible that the variable and functions inside the main function is accessible only by the names they are given at the time of returning. If one needs to access the value of “a” from outside then the call would be

saumyaJS.firstName;

But if one tries to access the value as

saumyaJS.a;

then one will get “undefined”!! This is how encapsulation works or simply, how one can hide values of an object in javascript.

This is a very basic concept of javascript, but I think this is the most important concept of javascript too.

Now we can see that whatever we want to access, we have to access through the “saumyaJS”, everything inside that function is not exposed outside or there is no more than one variable exposed to the outside world.

The source files are here to download and see for yourself. Hope that helps someone.

WordPress : backing up to Dropbox

I learned it the hard way that once you have a site up and running its better to keep a backup of the same locally in your machine. There are chances that the whole of the content might get erased!! You call it a server failure, no backup plan or anything, but the end result would be loosing all your content along with the conversations. In my quest to get a simpler and straight forward backup plan, I found this nice plugin for WordPress, called “WordPress Backup to Dropbox“. This plugin allows a direct, scheduled backup of the site to Dropbox. All one has to do is, schedule the time and frequency of backup and thats all, everything else is simply automated.
Hope that helps someone out there.

OpenPlug : ASlate, drawing application.

While learning OpenPlug|Studio and diving into the code, my third Android application is here. Its a simple drawing board, kind of slate. As an user one has option to select different color and pen thickness for drawing on it. Again a simple but usable application, which can be downloaded from this link.
The source code is availbale at Github too.

Using List component in OpenPlug

OpenPlug|Studio ships with its own SDK and though it seem like FlexSDK dependent, there are native components to work with for mobile devices. The major or the most used native component is List and one can access it as

mob:List id="allSDCardFiles" 
	x="0" y="0"
	height="100%" width="100%"
	rowHeight="45"

While it is expected to work fine and it does work fine in the simulator, but when tested on device (I have used an Android phone to test), the application simply crashed. Well the problem here is a bug in the baseSDK of OpenPlug. So till the bug is fixed the simple solution is to use a default itemRenderer. The fixed code will look as

mob:List id="allSDCardFiles" 
	x="0" y="0"
	height="100%" width="100%"
	rowHeight="45"
        itemRenderer="ListItemRenderer"
	

That simply works every where from simulator to the device.
Hope that helps someone out there.

My first workable Android application, AFinder.

On my quest with different tools/languages, I started on OpenPlug|Studio for developing in Android. Though this is a tool for developing for multiple devices, I specifically tried this for Android for the time being.
This IDE is based on Eclipse and there are two flavors of installations. One installs it directly as a standalone IDE and you have option to install it over FlashBuilder. The development is also based upon the same component style development as in Flex SDK. There is a different name-space for mobile specific UIs. they start with “mob” rather than “mx”. From compiling to publishing as an .apk file for android device installations are quite straight forward. The best part about the IDE is its completely free. Well then it has potential as to one codebase and publish to multiple platforms. The community at OpenPlug|Studio forum seems active too and one can feel there are a lot going behind as to fix up bugs and add new features to the tool set. Though there are bugs and features to be added, but as I said, once you involve in forum, you got to know they are already working on it and new releases are happening almost in 2-3 months.
Here is my basic Android application to move around your file system on the device. Would love to listen the feedback.