Pages

Showing posts with label JavaScript Tutorials. Show all posts
Showing posts with label JavaScript Tutorials. Show all posts

Accessing attributes

Consider HTML :
    
         <a id="techblog" href="http://netdweb.blogspot.com/">NetdWeb</a>



getAttribute is used to access the href attribute from the <a> element .      
   
          var elementvar = document.getElementById("techblog");
          var hrefattrib= techblog.href;



setAttribute method is used to set the value of attributes e.g.
  
               var elementvar = document.getElementById("techblog");
               elementvar.setAttribute("href", "http://netdweb.blogspot.com/");

Navigating Through the DOM

Since , DOM model is based on tree structure every element has a parent node (except document node) and every parent node has a child node .

parentNode

Consider this HTML :

         <p>
           <a id="techblog" href="http://netdweb.blogspot.com/">NetdWeb</a>
         </p>

 Here , <p> element is the parent element of the <a> element . To acces <p> from <a>  :


           var IDattrib= document.getElementById("techblog");
           var paragraph = techblog.parentNode;

 IDattrib variable refers to <a> element and paragraph variable to the parent node <p> .


 Since in a tree each child has only one parent but each parent can have many children  childNodes property references to all children of a parent . Suppose , if techblog is the Id of the parent node and you want to reference the fourth child of this parent :


                       var parentID = document.getElementById("techblog");
                       var childname = techblog.childNodes[3];


Keywords  firstChild and lastChild can be used to access the first and the last child of the parent . e.g


                        var first = techblog.firstChild;
 

                        var last = techblog.lastChild;



Nodes at the same level in the tree are referred to as siblings .  previousSibling and nextSibling are two keywords used to reference previous and next siblings . e.g.


                                                var x = y.nextSibling;

This stores next sibling to y in x .

                                               var a= b.previousSibling;

This stores previous sibling to b in a .

Working with getElementsByTagName

In order to work on multiple elements with same tag name  we use property  getElementsByTagName . e.g.


                               var listElements = document.getElementsByTagName("ul");

This stores all the elements with the tag name ul (unordered list) in the variable listElements . All elements inside listElements form a nodelist . listElements behaves like an array . So , to retrieve third elements in the variable listElements we use statement :

                                   var Thirdtem = listElements[2];

The third element in listElements is now stored in the variable ThirdItem .


To know the number of elements in the listElements we use statement :

                                     var totalItems = listElements.length;

Suppose you have two ordered lists and four unordered list elements  with two unordered list elements nested inside each ordered list and you want to retrieve  only the unordered elements inside  second ordered list . There is a way to get around this as :


                        var orderedlists = document.getElementsByTagName("ol");
                        var secondList = orderedlists[1];
                        var secondListElements = secondList.getElementsByTagName("ul");


We can use this approach to access any element in the document .

Getting elements by ID

ID is a unique name or number used by javascript to access particular element in HTML file .

                              var x = document.getElementById("color");

getElementById is used to access a particular Id specified in the brackets  i.e. color in this case . Variable x references to the particular element that has the ID color .


nodeName property


nodeName property is used to determine the type of element we are accessing through the ID e.g. in this case :


                      alert ( x.nodeName) ;

would return the type of HTML element to the window screen .

DOM: Document Object Model

Document Object Model treats each HTML element as a node in a tree and arranges all of them in the form of a tree data structure . Elements are arranged just like nodes are arranged in a tree with parent-child relationship determined by the nesting of the elements . A document node forms the root of the tree .

Element nodes further consist of  attribute nodes such as <a> element can consist of href and rel attributes . DOM model helps in easily applying various properties to a particular element or a group of elements .

Object Oriented Concept

Object Oriented programming involves segregating our entities into different classes . Objects are used to access the properties of classes . This provides security and is called encapsulation .  Objects having similar properties can be reused and classes can be easily extended .

In case of object oriented concept variables within a class are called properties and functions are called methods . A new object is created as :

                                                 var Color = new Object( );

Color is our newly created object in this case . The convention of using capital first letter for naming objects is used in this case .

Working with arrays

arrays are declared using square brackets a :

                                              var  name_of_array = [ ];
                                              name_of_array [0] = "Nadal" ;
                                              name_of_array [1] = "Federer" ;

If the array has two elements they are indexed as 0 and 1 within the [ ] . We always start with 0 and end at n-1 where n is the size of the array .


Arrays can also be declared as :


                                     var string_array = ["Andy", "Federer", "Nadal"];

Different data types can be combined in an array :


                                      var array_name = [ 10 , "Andy" , 34 ] ;




Array of an array



There can be an array whose elements himself are arrays e.g.


                                   var array1 = [ "Federer" , "Nadal" , "andy " ] ;
                                   var array2 = [ "Sachin " , "Ponting" , "Lara " ] ;
                                   var array3 = [ "10 " , "Lancer" , "30 " ] ;


                                   var array_of_arrays = [array1,array2,array3];
                                   var x = array_of_arrays[1,2];

array_of_arrays[1,2]
refers to 3rd element of array2 . Such arrays are also known as two dimensional arrays  .
Sometimes you need to know the length of the array . This is done as :
     
                                     var x = array1.length ;

This will store the length of array1 in variable x .

Associative Arrays

The indices inside the square bracket are not numbers but strings . These strings are more suitable to real life problems as it combines strings to strings  or strings to numbers or other arrays etc.  e.g.

                           
                                     var telephone_num = [ ];
                                     telephone_num["Andy"] = 9822334455;
                                     telephone_num["Federer"] = 9765443322;


Working with strings

+  operator is used to work with strings in javascript . + is used to combine strings or to append variables to a string . e.g.

                          var sentence = "You are " + var ;

This will append value  of variable to the string You are . e.g. if

                          var = "Andy" ;

then output will be  You are Andy .

In this case var is used to define a variable . Also JavaScript is a loosely typed language meaning you don't have to define a variable type by default such a int var or char var . JavaScript automatically assigns a data type to the variable .

Post increment vs pre increment

Post and pre-increment  can confuse many programmers . The best way to know the difference betwenn two is an example .

           Case1 :
                           var x = 10 ;
                           var y = x++ ;


What is value of y while it is being equated to x++ ?

            Case 2 :

                            var x = 10;
                            var y = ++x;


What is value of y while it is being equated to ++x ?

Answers :
Case 1 : 10
Case 2 : 11

Though note that when we move to the next statement value of both the variables will be 11 . Values vary only in case while the statement is being executed . In case there is no comparison operator values are same in both cases .

How to add javascript to web pages ?

There are three ways to add javascript to web pages i.e.

1)    Writing javascript code along HTML e.g.  <a href="xyz.html" onclick="JavaScript code">  where  onclick javascript event defines what action will be taken when user clicks on the xyz.html hyperlink .


2)   Adding javascript at the top of the html file  as :
<script type="text/javascript"><!--//--><![CDATA[//><!--JavaScript code //--><!]]></script> .
Don't worry if you don't understand it all .<!--//--><![CDATA[//><!-- //--><!]]> This part is for browsers to understand . To be put in simple language you can also do with  :
              <script type="text/javascript">JavaScript code</script>


3) Put your javascript code in a separate file and access it from your HTML file e.g.
             
                      <script type="text/javascript" src="abc.js"></script>
abc.js is the file that is accessed on the fly . .js extension is associated with the javascript files .
One of the advantages of using javascript in a different file is that you can apply same javascript  rules to different pages by calling the .js file from every page . src attribute is used to provide the location of the javascript file .

Three layers of web designing