While going ahead with javascript and all its goodness, we come across terms, which certainly make us curious like id and class. Apart from this we must know the things which we are going to use over and again as a web designer. When we already know about html,javascript and CSS makes up the whole web page, this is time to know some basics about CSS.
In CSS, we generally define some rules for our html content. Say, we have some structural data with a title and some content. Now this kind of data can be more than one in one page. So we will write some design rules, which our page content can refer to design itself. This kind of rules are called Class in CSS and generally defined with a . (dot) in the beginning.
.topic_title{}
.topic_body{}
The important thing to remember here is these elements will come more than once in a page. Now, there are elements in a page, which occur only once. These kind of elements are referenced as id and defined with a #.
#page_title{}
#page_navigation_menu{}
These are the basic types in CSS and we have already seen how these are referred in javascript too. To add the class styles and id styles in html document we write something as below.
We can even join two different styles together as
Now you can imagine how easy or complicated one can make a site design without even touching the content itself.
Well, there are some default elements in HTML as body, h1,p etc. These elements are directly designed with there name in CSS as
body{}
h1{}
p{}
How cool! Now for some global level elements or in general we have an option to define global style for all elements in a HTML page with a * as
*{}
That will assign, the designs described, to all the elements in the html page. This is, kind of, defining the base design of the page and its elements and then individual elements will override their design settings from there own id or class.
Point to keep in mind is, the design which is nearer to the element will override other design rules. That means, if there is a global style and an id or class style is defined for the element, the id or class style will override the design settings of the global style and the element will be visible as its defined in its id or class style.
While last post was about referring to an element in through only javascript. Here we will see how to access the same element with the popular javascript library, jQuery.
This is a tutorial straight from the jQuery site itself.
Lets start from the beginning as to add this library to our page. The code will look something like below, depending upon where you have placed your jQuery.js file.
Now lets see the old code of ours when we are doing an alert at the document load complete. The HTML file will look as
Hello World
Hello, this is first div.
Now the point here is to see that we removed the following from the HTML,
That means, HTML code will be pure content. There would be no functional elements inside HTML document. This helps maintain the documents for everyone. Now the code to do the same alert on document load will look as
$(document).ready(function(){
// Your code here
alert("Page is loaded");
});
Thats simple, but to keep in mind that jQuery gives a “$” to us. Everything we do with jQuery will start with a “$”. Though there are methods to override this, but basic will be using a “$”. And now the whole file will look as
Hello World
Hello, this is first div.
Next, jQuery allows a short hand of the same thing (action on document loading) and we can write that as below
$(function() {
// Handler for .ready() called.
alert("Page is loaded");
});
The above code is to select our first div on the HTML page.
And for the classes, jQuery allows us to do as below
$(".myClass")
This later thing will select all the elements which are given a CSS class named “.myClass”
These kind of things are called CSS Selectors of jQuery. Now you can understand the codes we have written before, which include a “$”.
Hope that helps someone.
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
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.
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.
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 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.
I will go on putting the details of my learning in the coming posts, but for the time being if one needs to play around the codes, please download and start researching.
Keep in mind that every language has its own way of doing things and the more ignorant you become (at least pretend to become) about other languages while picking up one, the faster you will master the one you are studying.
The example and source files convey, how to make and use your own javascript library, how to make a reusable Object in javascript (i am not saying to make a Class here, but a reusable Object, there is a very big difference in those two), how to make a basic CSS3 usage of rounded corners, multiple shadows, custom fonts and text shadows.
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.
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.