JavaScript - InshortsView

|
Divnesh BLOG
JavaScript course is designed to introduce the basic tokens of JavaScript and its object-oriented features. This course also deals with handling asynchronous requests using AJAX. It will help you to learn JavaScript through hands-on approach. script tag

After completion of this course you will be able to :

  • Write a program using JavaScript to solve a given problem with proper syntax and semantics
  • Apply DOM concept to access or manipulate a web page components 
  • Perform form validation using event handlers for a given requirement
  • Establish asynchronous communication between client and server using AJAX
Sign Up For Gmail Account - Error
On sign up page, while entering the details as shown below :
js1
If there is any mismatch while confirming the password, you will be seeing this error message.
Now the question is how this password matching happened instantly?
This is done by JavaScript, as the sign up page uses JavaScript for password matching.
JavaScript is a scripting language, which are mainly used to write scripts.
Scripts are nothing but programs that do not require any pre-processing like compilation before executing i.e. they are interpreted at run-time by browser. 
How to Add JavaScript in a Page?
As we have seen gmail signup page was having JavaScript for the password matching.
In order to have a JavaScript in a HTML page, we need to inform the browser that the page contains JavaScript content by placing them inside script tag element.
script element can be placed anywhere in our webpage, but it is usually preferred to be placed in head of our webpage.
script
 //JavaScript code goes here
/script
JavaScript code can even be defined in an external file and that file path is referred in the src attribute of script element.
script src="../JavaScript/sample.js"
	//No script goes here
/script
Defining a script in an external file helps in its reusability.
src attribute specifies the external file path as an URL which can be :
  • an absolute URL like http://www.javascript.com/sampleJavascript.js (refers to another web site)
  • a relative URL like /sample/sampleJavascript.js  (refers to a file within a web site)
    Note: To write something in a html page using JavaScript, we use document.write() . 
Basic Syntax of JavaScript
Before writing JavaScript code like password matching, let us first understand few important things about the syntax of the JavaScript language:
  • It is a case sensitive language
  • Semicolon(;) is used to separate statements
  • It considers spaces, tabs and new line characters as whitespace characters
  • It supports both single as well as multi line comments
//single line comment

/* multi line
 comment */
  • Identifiers (to identify a variable or function) can only start with alphabetic characters or "$" or "_" . Subsequent characters for the identifier can be alphabet or numeric.
           Example: number_of_trainees, catch22, _DB_ID
Datatypes in JavaScript
When we want to store some data in JavaScript, we should tell what exactly the data is and how we intend to use it.
Try to identify the datatypes that can be used in the gmail signup page
js2

JavaScript categorizes and stores the data based on the type of data. JavaScript supports mainly these data types:
  • Number : To represent numeric values ( Example : 12.5 etc. )
  • String : To represent text or sequence of characters ( Example : "Jack" ,'John' etc. )
  • Boolean : To represent Boolean values( Example : truefalse )
  • Null : To initialize a variable, which has no object to refer
  • Undefined : To initialize a variable which has no value for it
  • Objects : Its an collection of properties. Objects will be discussed in detail, later in this course
js3
Variables in JavaScript
We learnt to choose appropriate datatype for different input fields. To stores those values in browser memory for further processing we need variables. 
JavaScript is a dynamic typed language like Python. So we need not specify the data type while declaring a variable. The data type of the variable will be automatically determined when the script is executed.
This means we can have the same variable associated with values of different data types during the program execution.
For example , let us have a variable v1.
In JavaScript variables should be declared by using the keyword var.
var v1 = 23;           // v1 is now a variable of type Number
var v1 = "HelloWorld"; // v1 is now a variable of type String
var v1 = false;        // v1 is now a variable of type Boolean
Scope of variables is by default global. If a variable is prefixed by the keyword "var" within a function then it is a local variable.
var id=1001;         //Variable declaration. Type is decided by the usage
var name="Rajath";

document.write("h2");
document.write("Value of id is "+id+"br");
document.write("Value of name is "+name+"br");
//document.write() is used to display a message on the webpage
document.write("/h2");
Performing Operations in JavaScript
js4
Comparison and Unary Operators
In Comparison Operators we have === and !==. They are slightly different than == and !=.
=== returns true if both the operands’ value and type are equal, but == only checks if both the operands’ value are equal.
var x='1'; //String type 
var y=1; // Number type 
So, x==y will return true and x===y will return false
Same way != will check only if the value is unequal while, !== will check if both value and type are unequal.
In Unary Operators we have typeof. This returns the data type of the operand.
Using the same example as above:
typeof x;  //will return string
typeof(y); //will return number
new and instanceof Operators
There are also certain special operators like new.
This is used to create an instance of an object (can be user-defined or built-in).
var d = new Date(); //Here Date is a built-in object
In Relational Operators we have instanceof. This returns true if the object is of the specified object type.
var d = new Date(); 
d instanceof Date;    //will return true
var DA=2000;var basic = 10000;
var BoA=10000;
var PF=850;
var Gratuity=309;
var str="In hand you recieve a salary of Rs.";
var strTax="Tax you have to pay is Rs. ";
var today= new Date();
FixedSalary=Basic+DA+BoA+PF+Gratuity; //usage of operators
TakeHome=FixedSalary-(PF+Gratuity);
Tax=(FixedSalary>20000)?((7.5/100)*FixedSalary):((5/100)*FixedSalary);
document.write("

");

document.write(str+TakeHome+"br");
document.write(strTax+Tax+ br);
document.write("typeof var str is:        "+typeof(str)+"br"+"br");
document.write( "var today is instanceof Date: \t"+"     &nbsp");
document.write( today instanceof Date );
document.write("/h2");
Conditionals and Loops
Now that we know the various data types and the operators, we need to know how to perform decision making and repetitive tasks.
Just like in Java, JavaScript also has control structures which allow us to control the flow of execution in our program. They are:
  • Decision Making
  1. if
  2. if-else
  3. switch
  • Looping
  1. for
  2. while
  3. do-while
  • Branching
  1. break
  2. continue
  3. return
Conditional Statements
Syntax for conditional statements are as follows:
  • if
if (expression) {
    //statements
 }
  • if-else
if (expression) {
    //statements
 } else if{
    //statements
 } else{
    //statements
 }
  • switch
switch (expression) {
   case label_1: //statements
                 [break;]
   . . .
   case label_n: //statements
                 [break;]
        default: //statements
                 [break;]
}
document.write("h2");var num=3;
document.write("Cool Drinks vending machine br")
if(num>0 && num<5 td="">
document.write("Item is available for the pressed number "+num+"br");
switch(num){ //working of control structures
case 1:document.write("Item is Fanta");
break;
case 2:document.write("Item is Pepsi");
break;
case 3:document.write("Item is Coke");
break;
case 4:document.write("Item is Sprite");
break;
}
}
else{
document.write("No item is available for the pressed number");
}
document.write("/h2");
}
Looping Statements
Syntax for looping statements in JavaScript :
  • for
for (initial_expression; condition; increment/decrement_expression) {
    //statements
 }
  • for..in
 for (variable in object) {
    //statements
 }
  • while
while (condition) {
     //statements
}
  • do while
 do {
     //statements
} while (condition) ;
Dialog Boxes
JavaScript provides several dialog boxes to interact with the user.
  • Alert dialog box : It is mostly used for providing a warning message to the user.
    Example:
    alert("Hello!");
    Output:js5
  • Confirmation dialog box: It is used to take user's confirmation on any event.Confirmation dialog box returns a boolean value.
    Example:
confirm("Would you like to exit?");
Output:js6
  • Prompt dialog box : It used to take the input from the user, along with an optional message being displayed.A prompt dialog box can have a default value defined for the prompt.
    Example:
prompt("What is your lucky number?",0);
Output:js7
var name=prompt("Please enter your name","");
function display(enteredName){
if(enteredName!="" && enteredName!=null){
if(confirm("If entered name is "+enteredName+" , press OK to continue")==true){
alert(enteredName+" registered successfully");
document.write("h2 Welcome "+enteredName+"/h2")
}
}
else{
alert("Name is mandatory");
}
}
display(name);
User Defined Functions
We are already familiar with working of functions, now let us understand some interesting features of user defined functions in JavaScript :
In JavaScript, every function is an object(of type Function) and functions are treated as first-class citizens, as they can :
  • be stored in a variablearray, or object
  • have properties
  • be passed to, and returned from, another function
A function can:
  • return the value
  • If no return value is specified in a function, by default it returns 'undefined'
Also there is no restriction on the number of arguments passed to a function.
If we have passed extra parameters while invoking the function, those extra parameters can still be retrieved.
Creating Functions Using Function Statement
Function can be created either by using:
  • Function statement
  • Function expression
Let us understand how to create a function using function statement.
A function can be created using function keyword, followed by name of the function (functionName) and parameters(param1param2,…). After that it also contains the statements which forms the body of the function inside curly braces({}).
Syntax:
function functionName(param1, param2,…){
 //statements
}
Example:
function myFunction(num1,num2){ 
      num3=num1*num2;
 }
In the above example we have function named myFunction, which has parameters num1 and num2. The body of the function is placed inside the curly braces.
Now let us understand how to invoke the function defined in the previous example.
It can be invoked by using the name of the function (myFunction) and by passing necessary parameters.
myFunction(10,20);


eg
function myFunction(num1,num2){
alert("You are now inside a function")
num3=num1*num2;
document.write(num3)
}
myFunction(10, 20);








Function Expressions
Using function expression, we can create a function in two ways.
         1. Without providing the function name i.e. anonymous functions
         2. Providing the function name i.e. named functions
Let us first understand how to create an anonymous function.
A function can be created using the below syntax, which contains function keyword followed by the parameters(param1param2,…). 
function(param1,param2,…) {
   //statements
}
Anonymous Function
In the below example we have a variable named myFun, followed by the function definition.
var myFun = function(num1, num2){ 
       num3=num1*num2;                         
 }
In order to invoke an anonymous function, we need a named identifier. In the above example named identifier for the function is myFun
myFun(10,20);
Named Function
A named function can be created using the below syntax, which contains function keyword followed by the functionName and parameters(param1param2,…). 
var myFun = function functionName(param1, param2 ,…) {
    //statements
}
Let us understand with the help of an example.
var myFun = function myFunction(num1, num2 ) {
   num3=num1*num2;
}
In order to invoke a named function, we need a named identifier. In the above example named identifier for the function is myFun.
myFun(10,20);
How to Invoke Named Function?
Can we invoke the named function using its function name(myFunction) ?
A named function can be invoked by using its name myFunction, only when the function is invoked internally.
Otherwise if we are trying to invoke a named function outside its body, we should always use the named identifier (myFun) to invoke the named function.
When we have two ways to create a function, which is the most preferred one?
Functions expressions are very much easier to work with whenever we want to pass a function as a parameter to another function.
So if we want to pass a function as parameter, it is always preferred to create a function using function expression rather then function statement.
var myFun=function myFunction(num1,num2){
    num3=num1*num2;
    alert("calling myFunction internally");
    myFunction(num2,num3);
}
myFun(1,2)
Built-in Functions :
There are some functions which are already provided by JavaScript. These are known as built-in functions.
These functions that are predefined globally and so can be used with any JavaScript object.
built-in function.
  • eval() 
  • parseInt()
  • parseFloat()
  • Number()
  • String()
  • isFinite() 
  • isNaN() 

eval() built-in function.
eval() is used to evaluate the JavaScript code that has been represented as a string.
Syntax:
eval(string)
Example:
var x=2, y=2; 
eval("x * y")          //  4
eval("2 * 2")          //  4 
eval("z = new Date()")    // z=today’s date
parseInt()
parseInt() parses a string and returns an integer value of the radix specified (if not specified, default radix is 10 i.e. decimal number system).
Radix is the base in mathematical numeral systems like for Decimal (10), Hexadecimal (16), Octal (8) etc. Radix values can range from 2-36.
If parseInt() comes across a character in the string that is not a numeral, it will simply ignore it and all the other characters that are after it. Then it returns the integer value that it has parsed till that particular point.
Syntax:
parseInt(String, [radix])
Example:
parseInt("5");     // 5
parseInt("5.5");   // 5
parseInt("5p0");   // 5
parseInt("p50");   // NaN (Not a Number)
parseFloat()
parseFloat() parses a string and returns a floating point number.
If parseFloat comes across a character in the string that is not a numeral or '.' or '+' or '-' , it will simply ignore it and all the other characters that are after it. Then it returns the value that it has parsed till that particular point.
Syntax:
parseFloat(String)
Example:
parseFloat("1.23");    // 1.23
parseFloat(".123");    // 0.123
parseFloat("1.23abc"); // 1.23
parseFloat("a123")     // NaN 
Number()
Number(), which is the constructor of Number object, converts value of an object to a number. If it is unable to convert the value, it returns NaN.
Syntax:
Number(argument)
Example:
var x="123";					
Number(x);    	           // 123			
Number("123");	           // 123			
Number("123.1");           // 123.1			
Number(true);              // 1
Number(false);             // 0
Number("123abc");          // NaN
Number(new Date());       // number of milliseconds since January 1, 1970 
String()
String() converts the value of an object to a string. It is the constructor of the String object.
Syntax:
String(argument)

String(1)                       //  "1"
String(Boolean (0))             //  "false"
isFinite()
isFinite() determines whether given argument is a finite number or not.
If the argument is NaN, Infinity-Infinity then it returns false.
Syntax:
isFinite(Number)
Example:
isFinite(0)                 // true
isFinite(NaN)               // false
isFinite("Hi")              // false
isFinite("12Hi")            // false
isNaN()
isNaN() determines whether given argument is "NaN" or not.
If the argument to the function is not of type Number, then the argument is first coerced to a Number and then it is evaluated.
Syntax:
isNaN(value)
Example:
isNaN('12a');    // true
isNaN(12);       // false  
var a=isFinite(5-4); //true
var b=isNaN("4.4a"); //true
var c=isFinite(NaN); //false
Objects in JavaScript
In JavaScript an object is nothing but a collection of properties.
In simple terms a property is an association between a name and a value.
However the value can even be a function.
JavaScript provides many standard built-in objects. In addition to that it also provides an option to create user defined objects.
User defined objects in JavaScript can be created by using one of the following mechanisms.
  1. Using literal notation
  2. Using custom object constructor
  3. Using constructor of Object
Creating Object Using Literal Notation
Syntax:
var obj = { property1 : value1,
	     5  : value2,
	    "prop" : value3  }; 
  • obj refers to the name of the object to be created
  • Each property name can be an identifier, a number or even a string literal
  • Property value can be a constant or even an expression whose value will be assigned to the property
  • All the properties are wrapped inside the curly braces for better readability and understanding
Example:
var emp_one = {
    name : "John",
    empNumber : 1001,
    emailId : "Johny@123mail.com"
}; 
  • emp_one and its assignment is optional
  • If the object is not assigned to a variable (emp_one) then it cannot be referred anywhere inside the program
var trainee={traineeId:"329714",batch:"Jul15-LC1",stream:"JEE"}
document.write("h3 style='color:blue' Trainee object created using object literal notation/h3")
document.write("h3Trainee Details/h3")
document.write(trainee.traineeId+"br")
document.write(trainee.batch+"br")
document.write(trainee.stream)

Creating Object Using Constructor Function
An object can be created by using constructor function.
Syntax:
function Name(param1,param2,param3) {
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
};
var obj = new Name(p1,p2,p3);
Steps to create an object :
  1. Create a constructor function which provides details about the Name, properties and methods of the object type.
  2. Instantiate the object using new operator
Example:
function Employee(name,empNumber,emailId) {
    this.name=name;
    this.empNumber=empNumber;
    this.emailId=emailId;
    }
var emp_one = new Employee("John",1001,"John@infy.com");
Here we have created a constructor function Employee() to define the details about the object type. 
We also created an object of type Employee using the new operator.
Note:
  1. this is used to assign the values to the properties of an object.
  2. It is better programming practice to always start the name of constructor function(Employee) with a capital letter.
function Employee(name,empNumber,emailId) {
    this.name=name;
    this.empNumber=empNumber;
    this.emailId=emailId;
    }
var emp_one = new Employee("John",1001,"John@infy.com");
Creating Object Using Object Constructor
Syntax:
var obj = new Object([value]);
obj.prop1 = "value1";
obj.prop2 = value2;
obj.prop3 = "value3";
  • This object constructor creates an object wrapper for the [value] passed
  • If the [value] passed is emptynull or undefined this object constructor creates an empty object and returns the same
  • If [value] is passed, then it creates and returns an object of value type
  • It also allows the addition of properties for the objects created
Example:
var emp_one = new Object();
emp_one.name = "John";
emp_one.empNumber = 1001;
emp_one.emailId = "John@infy.com";
In the above example, initially we created an empty object using the Object().
After creating the object we added properties for the empty object (nameempNumberemailId).
For the emp_one object created above methods can be added and invoked as shown below.
emp_one.empDetails = function(){
// code goes here
}; 

emp_one.empDetails();
Let us have a look on one more example.
var obj = new Object(true);
 In the above example Object() constructor will create and return an object of type Boolean.
Accessing the Object Properties
create an object using literal notation.
var emp_one = {
    name : "John",
    empNumber : 1001,
    emailId : "John@infy.com"  }; 

Let us understand the different ways to access the object properties.
  • object.property
  1. To get the value: var name = emp_one.name;
  2. To set the value: emp_one.name = "Hello";
  • object[property]
  1. To get the value: var name= emp_one["name"];
  2. To set the value: emp_one["name"] = "John";
  • for..in : All enumerable properties can be accessed by using for..in loop with the below syntax.
    for(property in emp_one)
    {
    alert(emp_one[property]);
    };
    
How can we access only property names present in object in emp_one?
var emp_one = {
    name : "John",
    empNumber : 1001,
    emailId : "John@infy.com" };
In order to access only property names from the above object, Object.keys() function can be used.
keys() returns an array of property names of the object.
var props = Object.keys(emp_one);
Here props will contain an array of property names i.e nameempNumberemailId.
Note: object[property] access should be used mainly when the property names are having space, hyphen, or one that starts with a number.
Built-in Objects in JavaScript
JavaScript has several standard built-in objects which have a global scope.
  • Numbers and dates
    • Number*
    • Math
    • Date
  • Text processing
    • String*
    • RegExp
  • Indexed collections
    • Array
  • Structured data
    • JSON
Number Object
Number is a built-in object that allows us to work with numerical values.
Number object is created using the Number() constructor. 
Syntax:
js8
Some of the commonly used attributes and methods for you to explore are as follows:
  • Attributes
  1. Number.NaN
  2. Number.MAX_VALUE
  3. Number.MIN_VALUE
  • Methods
  1. Number.isFinite()
  2. Number.isNaN()
  3. Number.isInteger()
Math Object
Math is a built-in object that has properties and methods for mathematical constants and functions.
Math is not a constructor i.e. Math() does not exist. All its properties and methods are static.

Some of the commonly used attributes and methods for you to explore are as follows:
  • Attributes
  1. Math.PI
  2. Math.SQRT2
  3. Math.LN10
  • Methods
  1. Math.abs()
  2. Math.ceil()
  3. Math.floor()
Note: Math functions have a precision that's implementation-dependent which means that different browsers can give a different result.
var x=new Number("89");
alert(x +"  " +typeof(x));
var y=new Number("32wetf");
alert(y +"  " +typeof(y));
alert("isFinite() of x"+" "+ isFinite(x))
alert("isNaN() of y"+" "+ isNaN(y))
alert("minimum value in JavaScript"+ " " +Number.MIN_VALUE)
alert("maximum value in JavaScript"+ " " +Number.MAX_VALUE)

alert( Math.floor(5.2) )  

alert( Math.ceil(4.1) )   

alert( Math.round(3.2) )
alert( Math.random() ) 
alert(Math.tan(0.78))
alert(Math.sin(0.78))
alert(Math.cos(0.78))
alert(Math.pow(2,3))
Date Object
Date is a built-in object which is used to create a Date instance.
All Date objects are calculated using the number of milliseconds since 1 January, 1970 UTC.
Date instance can be created using Date() constructor. 
Some methods of object are: js10






Note: Month in Date is 0 based. js9























today=new Date();
alert("Today is (To locale string) :"+today.toLocaleString());
alert("toLocaleDateString()->"+today.toLocaleDateString())
alert("getdate()->"+today.getDate())
alert("getday()->"+today.getDay()) // day monday -1 friday -5
alert("gethours()->"+today.getHours())
alert("getminutes()->"+today.getMinutes())
alert("getmonth()->"+today.getMonth())
alert("getfullyear()->"+today.getFullYear())
alert("getseconds()->"+today.getSeconds())
alert("gettime()->"+today.getTime())

year=today.getYear();
nextyear=new Date((today.getFullYear()+1),0,1); // month starts from 0 - 11
days=(nextyear-today)/(24*60*60*1000);
String Object
String is a built-in object that allow us to work with string. A String object is created using the String() constructor.
Syntax :js11
js12
js13

Regular Expression
Regular Expressions are used for pattern matching.
The RegExp built-in object is used to create a regular expression object for pattern matching.
There are 2 ways to define a pattern:-
  • Literal way (creates a RegExp object):
    • The literal notation is compiled once and then used any number of times
    • This should be used when your regular expression does not need to change with time and remains constant           
     Example :
/E[1-9][0-9]{5}/
/E[1-9][0-9]{5}/ matches an employee ID starting with E with first digit between 1-9 and remaining five digits between 0-9
  • RegExp() constructor:
    • In constructor function, the expression is compiled at run time. We can use this when the pattern keeps changing
     Example :
new RegExp("E[1-9][0-9]{5}")
var s=new String("Hello");
alert(s)
s1=s.concat("World");
alert(s1);
alert(s1.toLocaleString().substr(5,5));
alert(s1.toUpperCase().substring(5, 11));
alert(s1.charAt(4));  
var s2=new String("Hello-World");
s3=s2.split("-") //here '-' is delimiter
alert(s3);

alert(/Java/.test("JavaStream"));  // Returns true
var re = new RegExp("Java");
alert(re.test("JavaStream"));  // Returns true 
Array Object
Array built-in object is used to create arrays.
Different ways to create an Array are:
var arr1 = [element0,element1,...,elementN];
var arr2 = new Array(element0,element1,...,elementN);
var arr3 = new Array(arrayLength);
Some of the attributes/methods of an Array object are given below:js14



eg
var courseArray = ['HTML','CSS','JS','JSF'];
courseArray.forEach(function PrintThis (value, index, arr)
 {
 alert("value :" + value);
 alert("index :" + index);
 }
);
courseArray.pop()
courseArray.push("Angular")
alert(courseArray)
JSON - JavaScript Object Notation
JSON is a data exchange format derived from JavaScript which is text based. link
It is mainly used in web based applications for data exchange like in web services.
Object Literal Notation

JavaScript Object Notation
var emp_one = {
    name : "John",
    empNumber : 1001,
    emailId : "John@infy.com"
}
var emp_one = {
    "name": "John", 
    "empNumber": 1001,   
    "emailId":"John@infy.com"
}

JavaScript provides a standard built-in object called JSON which has methods for parsing and generating JSON data.
parse():
var json = '{ "firstName":"Infosys", "lastName":"Limited", "pincode":570017 }';
var company = JSON.parse(json);            //will convert JSON string into an object 
alert(company.firstName +" "+ company.lastName +" "+ company.pincode );
 stringify():
var jScores = { "Java": 70, "JavaScript": 80, "CSS": 30 };  
var tScores = JSON.stringify(jScores);     //will convert object to JSON
alert(typeof(jScores));                   // returns Object
alert(typeof(tScores));                   // returns String 
var trainees = { "Trainee" : [ 
   { "Name"  : "Ram", "age" : 34 },
   { "Name"  : "Raj", "age" : 23 }],  			
}    
alert(trainees.Trainee[0].Name)
alert(trainees.Trainee[1].age)

var json = '{ "firstName":"Infosys", "lastName":"Limited", "pincode":570017 }';
var company = JSON.parse(json);            //will convert JSON string into an object 
alert(company.firstName +" "+ company.lastName +" "+ company.pincode );

var jScores = { "Java": 70, "JavaScript": 80, "CSS": 30 };  
var tScores = JSON.stringify(jScores);     //will convert object to JSON
alert(typeof(jScores));                   // returns Object
alert(typeof(tScores));                   // returns String 
DOM - Document Object Model
Consider the gmail sign up password matching logic. In order to develop this logic, we need to know how to access the values of password and confirm password fields in JavaScript.js15
The values of these fields can be accessed with the help of DOM.
DOM (document object model) acts as a programming interface between HTML and JavaScript.
  • It turns HTML tags to objects, which can be accessed and manipulated by JavaScript
  • Our browser parses the HTML document and turns it into the DOM representation
js16
Here the DOM objects are shown along with the HTML code.
Before we can learn to access these DOM objects(also known as Nodes), we will see how they are arranged in a hierarchical fashion.
Note : Window object depicts our browser. It is root node for the rest of the objects. 
DOM Hierarchy
js17
This is a simple hierarchy of the few important objects.
Let us see how we can access these objects in our JavaScript code by following this hierarchy.
Consider the code below :
form name="userlogin" 
	     Usernameinput type="text" name="username"
	     Passwordinput type="text" name="pass"
/form
Here, the value in the Username textbox can be accessed in the JavaScript code as
js18
We know that every HTML document is represented by a Document object in a web browser.
DOM Properties and Methods
js19
To use any method or property, we have to use it in document.write() or document.URL format
Every form element present in a document is represented by a form object in DOM.
Note : console.log is used to print output in browser's console. Console can be viewed by pressing F12 in Chrome.
var sAnswer = window.prompt("Please enter your favorite color : choose from the following Yellow, Green, Red, Blue, Pink, Orange, Black, Grey");
document.bgColor = sAnswer;
document. write ("H1Welcome to " + sAnswer + " background :-)!!/H1HRWe are very happy to demonstrate the usage of  document. write. Do remember to view the source!");
HTML Form as DOM Object
Let us now see the form object and various elements present in it.
Consider the code below:

            
        FormObjectDemo
    
    
        
  Yes   No  
 
 
Let’s see the various ways by which we can access the form elements.
Let us take the example of the first radio button value. It can be accessed as either of the two ways
  • by referring the name of the element
document.form1.rad1[0].value
  • by referring from the forms collection and elements collection
document.forms[0].elements[0].value
js20
  • action attribute is used to specify the action page URL
  • Each form element in a document generates a form object
  • Can be accessed using forms[] collection attribute of its parent document
form name="register"
 Enter username .input value="John" id="name" name="username".
/form
to fetch the value entered in username text field
  • document.getElementById(“name”).value
  • document.register.username.value
Event Handling
Consider the gmail sign up password matching logic.
After entering the value for 'confirm you password', to invoke the function containing the logic we can make use of events and event handlers
js21
Every action of a user or browser causes events on a web page. 
HTML elements for which we want to handle the event, can specify event attributes.
Let us see, some of the common events and its corresponding event attributes.

We expect our page to respond accordingly to these events(isn’t that’s why we started with JavaScript, to make our page interactive).
The JavaScript code(called specifically as function) is written to respond to these events are called as event handlers.
The general syntax to define an event handler is:
event-attribute
 = "JavaScript-code-or-JavaScript-function">
Example 1:
p onclick="alert('hello');"Click me/p

Example 2:
script type="text/javascript"
 function sayhello(){
   alert('hello');
 }
/script
p onclick="sayhello();"Click me/p
Note : Function invoked on triggering an event can also be a validation function.

Event Handling : Custom Message
For a form like below, we will usually enter our name in the given text box.
If we provide the name in the wrong format, error message is displayed as shown below.
To provide a user friendly experience, the message should clearly state your requirements.
  • Custom message for an UI component can be set by using element.setCustomValidity('error message') 
  • When an invalid event is triggered, our 'error message' will override the existing message 
Let us understand this with an example.
Custom Message Example
js25
Synchronous Request
Synchronous request means once a request is sent to the server, one has to wait until the response arrives before sending the next request to server.
  • Till the request is not completely processed client will not be able to send next request
  • JavaScript engine of the browser will be blocked
  • When the response arrives, whole page needs to be refreshed at the client side
  • js26
In the above example only after entering all the details, request can be sent to the server. The sign up page can send another request, only after getting the response(like 'Username already exists') for the previous request. In order to render the response the page needs to be refreshed.   
For every new request above process will be repeated, which is time consuming and inefficient.
Asynchronous Request
Whereas in asynchronous, multiple requests can be sent at any time without waiting for the response from the server.
Here client is sending multiple requests, not to the web server directly, but to the AJAX (JavaScript code) which will further make call to the web server, so that client will not get blocked in-between multiple requests.
Multiple asynchronous communications between client and server may occur simultaneously with one another.
js27
In the above example we need not completely fill all the details in the sign up page for sending the request to the server.
Just after entering the user name, a request can be sent to the server.  
The response from the server can be rendered, even without refreshing the page.
Multiple requests can be sent to the server without waiting for the responses of the previous requests.
AJAX - Asynchronous JavaScript and XML
Now we know the advantages of asynchronous requests over synchronous requests.
But how asynchronous requests are handled?
Using AJAX (Asynchronous JavaScript and XML).
It is a group of inter-related technologies like HTML, CSS ,JavaScript, DOM etc.
  • HTML : To built web pages and forms
  • CSS : To style the content of the page
  • JavaScript : The complete functionality of AJAX is written in JavaScript code. It will help the webpage in interacting with the server
  • DOM : It is used to access the html documents using JavaScript
The combined use of HTML,CSS, JavaScript and DOM makes the document a Dynamic HTML.
  • It eliminates monotony of static web pages
  • It make a webpage more interactive without reducing the performance
  • It gives more control over the HTML elements and web content to change them at any time, without reaching to the web server
AJAX - espncricinfo
AJAX helps a Web application to make a request only for selected content that needs to be updated in that page.
Let us understand more with the example of a website where cricket score is updated dynamically.
Example: espncricinfo.com
Here for every ball, the scorecard and commentary gets updated automatically and every other part of the web page remains the same.
AJAX - Twitter
Let us look at another scenario of social networking site like twitter.
Whenever we sign up on this website, it always asks us to provide a unique username. Ever wondered how does it instantly checks whether the username provided is already used or not.
XMLHttpRequest Object
By now you would have understood the AJAX mechanism.
But who exactly is responsible for sending the asynchronous request and handling the corresponding response?
Answer is the XMLHttpRequest object.
  • It handles all the communication to and from the server and helps in fetching resources
  • It is an HTTP API. But it can even be used with protocols other than HTTP
  • It supports the following data formats:  XML, JSON, HTML, plain text
  • It supports all activities involved with HTTP requests or responses and allows the client to interact with the server using below methods and attributes
Attributes and Methods of XMLHttpRequest object.
js28
js29
How to Build AJAX Application?
images all














XSS Vulnerability
Responsive web pages handle information related to end user.
Example : username and password.
And these information needs to be protected. Information assurance is the practice towards achieving the same.
vulnerability is a weakness of system which when exploited can reduce that system’s information assurance.
These vulnerabilities can give way to attacks with intend to access and manipulate application as well as sensitive information.
Attackers can exploit these vulnerabilities to extract user’s private data, like cookies or other session information.
One such vulnerability is Cross site scripting (XSS). It is one among the ten most critical web application security risks as per OWASP Top 10 – 2013.
Cross-Site Scripting (XSS) attacks are nothing but injecting an attack code on to the client-side.
Let us learn when these vulnerabilities can occur.
XSS vulnerabilities may occur when :
  • Inputs provided to the web app are not validated
  • HTML encoding is not applied, then the browser interprets output as code
These XSS vulnerabilities can be prevented by following the below rules:
  • Validation to filter out the user input. Then the browser interprets it as code without malicious content
  • Encoding escapes the user input only as data, not as code so that the browser interprets accordingly

Google application security website has complete description about cross site scripting, click here to explore.

JavaScript comes with some built-in functions. To use them, we just need to invoke them.
Let us explore some of these built-in functions to understand their significance and usage.
Built-in functions   
Description
Syntax
alert()
It throws an alert box and is often used when user interaction is required to decide whether execution should proceed or not.
alert("Let us proceed");
confirm()
It throws a confirm box where user can click "OK" or "Cancel". If "OK" is clicked, the function returns "true", else returns "false".
var decision = confirm("Shall we proceed?");
prompt()
It produces a box where user can enter an input. The user input may be used for some processing later. This function takes parameter of type string which represents the label of the box.
var userInput = prompt("Please enter your name:");
isNaN()
This function checks if the data-type of given parameter is number or not. If number, it returns "false", else it returns ""true.
isNaN(30);       //false
isNaN('hello');  //true
isFinite()
It determines if the number given as parameter is a finite number. If the parameter value is NaN,positive infinity, or negative infinity, this method will return false, else will return true.
isFinite(30);     //true
isFinite('hello'); //false
parseInt()
This function parses string and returns an integer number
parseInt("10");         //10
parseInt("10 20 30");   //10
parseInt("10 years");   //10
parseInt("years 10");   //NaN
parseFloat()
This function parses string and returns a float number
parseFloat("10.34");      //10.34  
parseFloat("10 20 30");   //10
parseFloat("10.50 years"); //10.50

eval()
It takes an argument of type string which can be an expression, statement or sequence of statements and evaluates them.
eval("var num1=2; var num2=3;var result= num1 * num2;console.log(result)");








Featured Post

HTML cheetsheet

List: Link tgs Dropdown

Popular Post

(C) Copyright 2018, All rights resrved InShortView. Template by colorlib