JavaScript Tutorial

Javascript Tutorial

JavaScript Tutorial

1. Javascript is client side programming language for web.

2. In Web, HTML refers to a structure of the website, CSS adds style to the website for look and feel and Javascript makes the user interact with the web.

For Example: Form Validation, event call on onclick.

3. JavaScript is a single thread language which means it’s executed line by line.

For Example: if we execute A, after a particular time (setTimeout) executes B, then execute C.

The output is A, C, B. This is because it reads line by line.

4. JavaScript is an open source language so we can implement it in cross-platform also. It was invented by Brendan Eich in 1995. Javascript versions are denoted ES or ECMA Script. The latest Version of Javascript is ES6.

5. Javascript Consists of a lot of frameworks such as Angular, React js, Create JS(Game Engine) and library such as Jquery, D3js, etc.,

JavaScript Tutorial for Beginners | GangBoard

6. Execute javascript, HTML by using internal or external.

For internal – include <script></script> tag in head or body section.

For External – write code in separate file with .js extension and include it in header part <script src=”main.js”></script>

7. Javascript reads the DOM structure of HTML, so we can easily add or remove the element.

8. Development tools for javascript are Notepad++, Dreamweaver, visual studio code.

9. Because of the development of html5, we can convert flash files( such as flash games, e-learning) to HTML 5 using Javascript. Because of security reasons not used on the networking side.

10. Read the data from the server and send them in the background without reloading the page by using the AJAX method. XML and JSON are used to store and exchange the data in the text. HTML 5 games are done by using Javascript.

1. Javascript Overview

The codes placed within a script tag are

called javascript. The Script tag should be closed whenever the code ends.

The type is to mention that the code is javascript.

<script type = "text/javascript">
// Your Code here...
</script>

Semicolon :

Every javascript line should be terminated with Semicolon at the end of the statement. In the below example we have created a variable using keyword var and terminated with a semicolon. A semicolon is an option but we need to follow the standards.

<script type = "text/javascript">
var x = 10;
</script>

Javascript is a Case sensitive language which means,

<script type = "text/javascript">
var a = 10;
document.write(A);
</script>

Here we have declared the variable as a (lowercase) but we have printed the value is A (Upper case), Javascript will treat both as different variables.

2. Javascript Syntax

Javascript syntax has some set of rules.  Javascript can be written in a script tag of HTML or link the javascript file in the script tag.

Example:
<script ...>
document.write('hello world')
</script>
or
<script src='custompath/filename.js'>
</script>

Semicolons:

after statements in javascript followed by semicolons like c, C++, Java.  we can also omit semicolon for best practice use semicolons.

Example:
<script language = "javascript" type = "text/javascript">
// normal way
var int1 = 10;
var int2 = 20;
// without semicolon
var string = 'hello'
var string2 = 'world'
</script>

Comments:

JavaScript comments are like C and C++. For single line comments, use ‘//’ double slash.

Example:
// this is single line comment
For  multi line comments use  /* */
Example:
/*
this all lines are written
inside of multiline comments
*/

Case sensitivity:

javascript is a case sensitive language. Keywords, variables and function names are all case sensitive.

Example:

variable name int and INT are different.

WhiteSpace:

javascript neglect spaces tabs and new lines in the code. so we can use multiple spaces that will not make any problem.

Keywords:

keywords are used to identify actions to perform, many keywords are in javascript. Don’t use keywords name to any functions and variables.  some of the keywords are var, let, const, function, if, for, while, break, etc.

Camelcase:

we can join multiple words in the single variable name.

  • upper camelcase like FirstName. mostly we will use this in constructor function creation.
  • lower camelcase like firstName. all the variables, functions we can use lower camelcase.

Operators:

  • Arithmetic operators are ( +, -, *, %) to compute values in javascript.
  • assignment operators(=) are used to assign values to variables for eg. var a = 10;

3. Javascript Placement in HTML File

In HTML we can place javascript anywhere but the standard is to place the javascript code within head tags.

We can place these codes in the head tag, body tag and in the javascript file.

head tag

<head><script>
// Your Javascript code here.....
</script>
</head>

body tag

<body><script>
// Your Javascript code here.....
</script>
</body>

Include javascript page in HTML page :

We can also write a javascript code in javascript file with the extension of .js (myscript.js) and we should include the file in the head tag of an HTML file as follows,

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

myscript.js :

Within the myscript.js file, we should write the script as follows and we don’t need to include script tag.

function Welcome(){
document.write(""Besant Technologies";")
}

4. JavaScript Variables

Javascript variable is nothing but it’s a container, we can store data within it.

var x=20;

here,

var – datatype,

x – variable name,

20 is the value of x.

From the above example, we stored 20 into variable x.  A variable must be unique. It won’t allow duplicate.

We can store any type of data in this var type (like int, float, char, string, etc,.)

Example:
var x=30;   //int variable declaration
var f=3.14;  // float variable declaration
var s=’hello javascript’; //// string variable declaration within single quotes
(or)
var s=”hello javascript ”;  // string variable declaration with in double quotes

5. JavaScript Operators

Operators are always play crucial role in programming language. We perform any mathematical or any special operation in programming it helps to utilize.

There are four types of Operators:

  1. Arithmetic Operators
  2. Assignment Operators
  3. Logical operators
  4. Comparison Operators
  5. Conditional Operators

Arithmetic Operators:

The operators used to do the arithmetic operations specified as arithmetic operators. It seems to perform mathematical operation like Addition, subtraction, multiplication, division and module.

Operator Description
+ Add
Sub
* Multiplication
** Exponentiation
/ Div
% Modulus (Division Remainder)
++ In

crement

Decrement
Example 1:
var x = 5;
var y = 2;
var z = x + y;
Example 2:
x+y , x-y,x*y, x/y,x%y
Assignment Operators:

Operators used to assign the values to the JS variables. It is also known equal operator.

Like +=, -=,*=,/=,%= etc.

Operator Example Same As
= A = B A = B
+= A += B A = A + B
-= A -= B A = A – B
*= A *= B A = A * B
/= A /= B A = A / B
%= A %= B A = A % B
**= A **= B A = A ** B
Example 1:
x+=y, x-=y, x*=y
Example 2:
var x = 1;
x += 5;

Comparison Operators:

Operators are used to compare the both sides. It supports the following comparison operators:

Like equal(==) ,not equal(!=), greater than (>),less than(<)

Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
Example 1:
(x==y), x!=y, x>y, x<y
Example 2:
Case Value
1 < 21 TRUE
1< “21” TRUE
1 < “Smith” FALSE
1 > “Smith” FALSE
2 == “Smith” FALSE
“1” < “21” FALSE
“1” > “21” TRUE
“2” == “12” FALSE

Logical Operators:

Operators used to do the logical checks. It seems to check the logical condition, check  whether the condition is true or false.. Like &&(and),||(Or),!(Logical not)

Operator Description
&& logical and
|| logical or
! logical not
Example 1:
x&&y ==0, x||y!=0
Example 2:
Operator Description Example
&& And (A < 10 && B > 1) is true
|| Or (A == 5 || B == 5) is false
! Not !(A == B) is true

Conditional Operators:

Conditional operator uses (?:) for true or false, it executes two or more statements.

6. JavaScript ifelse Statement

IF Else Statement always use to make decision of program and handle all the correct actions. JavaScript uses if else conditional statement which perform different actions.

if

When the single condition is available, then we can use the if condition check. It always use to make decisions and execute statement conditionally.

Syntax
if(condition)
{
//set of code to execute, when the condition is true.
}
Example:
If(day==”monday”)
{
day=”weekday”;
}

else

Else block is not mandatory to follow the if, but when there is an either or Situation. Then we should use the else followed by if.

else will execute once the if condition is false.

Syntax:
if(condition)
{
//set of code to execute when the condition is true.
}
else
{
//set of codes to execute when the condition is false.
}
Example:
if(day==”sunday”)
{
day=”weekend”;
}
else
{
day=”weekday”;
}

else if

When we have more than two conditions, then we have to choose the ELSE IF.

Syntax:
if(condition)
{
//set of codes to execute when the condition is true
}
else if(condition)
{
//set of codes to execute when the condition is true
}
else
{
//set of codes to execute , when both the above conditions are false
}
Example:
if(day==”saturday”)
{
outputText=”Last day of the Week”;
}
else if(day==”sunday”)
{
outputText=”First day of the Week”;
}
else
{
outputText=”Weekday”;
}

if else if statement

It allows JavaScript to make correct decision out of several conditions.

Syntax:
If (expresson 1)
{
//Statements
}
Else if
{
//Statements
}
Else
{
//Statements
}

7. JavaScript Switch Case

Switch case is nothing but long if else statement, means we can use switch instated of long or multiple if statement .  It can have multiple cases and last one default case(optional).

Switch case is always been used to execute expression or condition along with variable specification..

Switch case is converting the specific data into cases:

For instance:
Switch(Condition/Expression)
{
Case 1:
//Provide statement;
Case 2:
//Provide statement;
Case 3:
//Provide statement;
Default:
//Statement
}

Rather it gets the case, however it does not find the case control move on to default it will always been true except all the cases.

Example:
<script type=”text/javascript”>
var class=’First’;
switch(class)
{
Case ‘First’:document.write(“First class”);
Break;
Case ‘Second’:document.write(“Second class”);
Break;
Case ‘Third’:document.write(“Third class”);
Break;
Default: document.write(“unknown class”);
}
</script>

Switch case checks the expression and identify the case, then it will start to execute all the statements between case and break statement.

Syntax:
switch(expression)     // Given expression by user{
case  p:
// statements
break;
case q:
// statements
break;
defult:
//statement
break;
}
Example:
var n=’a’;Switch(p)
{
case ‘a’:
value=’Addition’;
break;
case ‘s’:
value=’subtraction’;
break;
default:
value=’check your input’;
break;
}

Rules:

  1. Switch case can support multiple data types.
  2. Break statement and default case are optional.
  3. We can’t check condition, only expression.

8. JavaScript While loop

While loop is always execute the statement or code repeatedly. It always return true if condition is true. Instead of If statement, We can get enhance if, which is called while loop. It never works without condition or expression. Providing some condition it will easily work to get proper outcome.

The while loop executes a block of statements repeatedly as long as the condition is true. First iteration in while loop executed with no condition check. Second iteration will be executed only if the condition succeeds. If condition fails, the loop terminates.

Syntax:
while (condition)
{
Statements;
}

Note: If the condition is always true, the loop will never end. This will crash your browser. So there must be variable initialization and variable increment / decrement.

Example 1:
var Result = "";
var i = 1;
while (i < 5) {
Result += "<br> number: " + i;
i++;
}
Output:
number: 1
number: 2
number: 3
number: 4
Example 2:
Var counter=0;
While(Counter<10)
{
Document.write(Counter);
Counter++;
}
Example 3:
<script type=”text/javascript”>
var counter=0;
while(counter<10)
{
Document.write(“Current Count:”+counter+”<br/>”);
}

9. JavaScript for loop

For loop is most import concept in each and every programming language. It always contains loop initialization, test statement, iteration statement.

For loop is been used to initialize or traversing the data along with  condition.. Either defined increment or decrement operator at the end of conditions.

The for loop executes a block of statements repeatedly as long as the condition is true.

Functionality wise both “While” and ”for” are same. The difference is the place where initialization and increment / decrement happen.

For loop has following fields

Initialization:

Here you mention where the loop should start from. You can declare a new variable and initialize it to zero to begin the loop from value zero

Condition check:

Only if this condition is satisfied, execution goes inside for loop. If condition fails, execution goes out of for loop (the loop terminates)

Increment:

It increments the value that we initialized in the initialization part of for loop.

Syntax:
for (statement1; statement2; statement3)
{
Statements;
}
Where,
statement1 : variable initialization
statement2 : condition
statement3 : increment / decrement
Example:
var Result = "";
for (var i=1; i < 5; i++) {
Result += "<br> number: " + i;
}
Output:
number: 1
number: 2
number: 3
number: 4
Example:
var array = [‘apple’,’mango’,’banana’]
for(let i=0;i<array.length;i++){
console.log(array[i])
}
Output:

How it works?

Step1: Execution starts with initialization and condition check.

Step 2: Once first iteration gets over, executions goes to increment part then checks for condition.

Step 3: Only if the condition is satisfied, it goes inside loop. If condition fails, the loop terminates.

Loops

To execute a block of code for different values we use Loops. There are different loops which serve the same purpose. To apply same logic to different values or n number of values, we use Loops.

For Loops

To perform the same functionality on different values we use loops. Out of other loops, For Loop is so compact to use. It is used on Arrays. It has following fields.

Example:
Var a;
For(a=0; a<10; a++)
{
Document.write(a);
}
Syntax:
For(initialization; test statement; iteration)
Example:
For(i=0; i<=10; i++)

Program of For Loop:

<script type=”text/javascript”>var couter=0;
for(counter=0; counter<=10; counter++)
{
Document.write(“Current count:”+counter);
}
</script>

10. JavaScript for…in loop

For..in is used to loop over the properties of an object.The set of code inside the loop will be executed for each property of an object.

Syntax:
for (variable in object)
{
Statements;
}
Example 1:
var address = {city:"Chennai", state:"Tamil nadu", country:"India"};
var text = "";
var x;
for (x in address) {
text += address[x] + "<br>";
}
Console.log(text);
Output:
Chennai
Tamil nadu
India
Example 2:
var company = {firstName:"Besant", lastName:"Technologies", age:100};
var text = "";
var x;
for (x in company) {
text += company[x] + " ";
}
Output: Besant Technologies 100

We can’t use for..in statement to loop array values but index order is important. Below example demonstrate the reason for that.

Example:
var arraylist = [];
arraylist [5] = "Hello";
console.log("for...of:");
var count = 0;
for (var item of arraylist) {
console.log(count + ":", item);
count++;
}
console.log("for...in:");
count = 0;
for (var item in arraylist) {
console.log(count + ":", item);
count++;
}
Output:
for...of:
0: undefined
1: undefined
2: undefined
3: undefined
4: undefined
5: Hello
for...in:
0: 5

For..of loop properly worked on with index value. But for..in.can’t do that.

JavaScript Loop Control

Loop control statements deviates a loop from its normal flow. All the loop control statements are attached to some condition inside the loop. JavaScript provides statements like “break” and “continue” to control loops.

Break  Statement

Break statement is used to break the loop on some condition. Used to to jump out of a switch / loop.

Syntax:
For Statement
For(initialization;condition;Increment/decrement)
{
If(condition)
{
Break;
}
Statements;
}
While Statement
Initialization;
While(condition)
{
If(condition)
{
Break;
}
Statements;
Increment/decrement;
}
Example 1:
for(var i=0;i<20;i++)
{
if(i==5)
{
break;
}
console.log(i);
document.write(i+"<br>");
}
Output:
0

1

2

3

4
[/su_table] The loop should print from 1-20.But inside loop we have given a condition that if value of  I equals to 5, then break out of loop. It will break the loop when its reach 5.

Example 2:
for (i = 1; i < 5; i++) {
if (i === 2) { break; }
text += "number:" + i + "<br>";
}
OUTPUT:
Number:1

Continue Statement

Used to skip the current iteration and continue with next iteration.

Syntax:
For Statement
For(initialization;condition;Increment/decrement)
{
If(condition)
{
Continue;
}
Statements;
}
While Statement
Initialization;
While(condition)
{
If(condition)
{
Continue;
}
Statements;
Increment/decrement;
}
Example 1:
for(var i=0;i<10;i++)
{
if(i%2==0)
{
continue;
}
console.log(i);
document.write(i+"<br>");
}
Output:
1
3
5
7
9

In above code when i value becomes an even number , continue forces the loop to skip without further executing any instructions inside the for loop in that current iteration.

Example 2:
for (i = 1; i < 5; i++) {
if (i === 2) { continue; }
text += "number:" + i + "<br>";
}
Output:
Number:1
Number:3
Number:4

Javascript labels using loop control

The break statement , without a label reference used to escape from loop or switch statement. With label reference it can be jump out any code block.

Syntax:
Label:
Statement;
For break
Break Label;
For continue
Continue Label;
Example 1:
var fruitlist = ["apple", "orange", "grapes", "banana"];
var text = "";
list: {
text += fruitlist[0] + "<br>";
text += fruitlist[1] + "<br>";
break list;
text += fruitlist[2] + "<br>";
text += fruitlist[3] + "<br>";
}
document.write(text+"<br>");
Output:
apple
orange
A code block is a block of code between { and }.

12. JavaScript Functions

A Function is a set of instruction or code that is used to perform a particular task. It is will execute the code when it is called or invoked. A function is a group of the reusable system which can be charged everywhere into your program. This eliminates the requirement for employing this immediate again.

Function Definition

The most common method to determine use in JavaScript is by using this function keyword, supported by a different function name, a report from parameters and an information block enclosed by curly braces.

<script type = "text/javascript">
function functionname(parameter-list) { }
</script>
Example:

It represents a function called sayHello that receives no parameters

<script type = "text/js">
function sayHello()
{ alert("Hello World!"); }
</script>

Calling a Function

To invoke a party somewhere later in this script, you would only need to write that name from that use as shown in this following system.

<html>
<head>
<script type = "text/js">
function sayHello()
{ document.write ("HelloWorld!"); }
</script>
</head>
<body>
<p>Click the button for call back</p>
<form>
<input type = "button" onclick = "sayHello()" value = "SayHello">
</form>
<p>different type write method</p>
</body>
</html>
Output

Function Parameters

Till now, we have discussed functions without parameters. But there is a means to give different parameters while declaring a function. A celebration can take many parameters separated by a comma.

<html>
<head>
<script type = "text/js">
function sayHello(name, age)
{ document.write (name + " is " + age + " years old."); }
</script>
</head>
<body>
<p>Click the call button</p>
<form>
<input type = "button" onclick = "sayHello('Vignes', 29)" value = "Say Hello">
</form>
</body>
</html>

Return Statement

A JavaScript use can should an optional interest statement. This statement should remain that last statement toward a function.

<html>
<head>
<script type = "text/js">
function concatenate(first, last)
{ var full; full = first + last; return full; }
function secondFunction()
{ var result; result = concatenate('Besant', 'Technologies');
document.write (result ); }
</script>
</head>
<body>
<p>Click the function button</p>
<form>
<input type = "button" onclick = "secondFunction()" value = "Call Function">
</form>
<p>parameters inside function</p>
</body>
</html>

13. JavaScript Events

JavaScript’s interaction with HTML remains managed through forces that occur when an individual user or the browser form a page.

Events are a part of a specific Document Object Model (DOM) Level 3 moreover every HTML element includes a number of events which can trigger JavaScript Code.

Events are states of change on html controls. We can execute the javascript code when an something changes occurred in html controls occurs. It may does by user or browser.

Example of Events

  1. HTML page finished loading
  2. When click on the button
  3. When mouseover the content or HTML Controls.

When particular events occur we can execute the javascript code.HTML event handler attributes available for HTML tags

Syntax:
<tagname event=”JS  call”>
Example:
<input type=”button” onclick=”Welcome();”>
When button is clicked, It will call the javascript welcome function.

Common events

1.Onclick – It will fire when click event happen.

2.Onsubmit – It will fire when submit event happen

3.OnMouseOver- When over the content

4.Onload – When HTML page finished the loading

5.Onmouseout – When mouse out the controls.

6.Onchange – when input value was changed.

7.Onkeydown – when Keyboard key pressed

Example:
<html>
<body>
<script type = "text/javascript">
function addition(num1,num2)//this is parameter
{
document.write("Addition value is: "+(num1+num2));
}
</script>
<input type="button" onclick="addition(56,78);" value="Addition">
</body>
</html>
Output:

When click the Addition button it will shows:

Addition value is: 134

Onclick Event Type

This is the common usually utilized event model which occurs when a user clicks the extra button of his mouse.

<html>
<head>
<script type = "text/javascript">
function sayHello() {
alert("Hello")
}
</script>
</head>
<body>
<p>Click the Button</p>
<form>
<input type = "click Button" onclick = "sayHello()" value = "SayHello" />
</form>
</body>
</html>

onsubmit Event Type

onsubmit is an effect that occurs when you try to offer a form. You can put your order validation upon this match type.

Example:

If validate() function turns true, the order will be submitted, otherwise, it commands not submit the data.

<html>
<head>
<script type = "text/js">
function validation() {
}
</script>
</head>
<body>
<form method = "POST" action = "t.cgi" onclicksubmit = "return validate()">
<input type = "submit" value = "clickSubmit" />
</form>
</body>
</html>

onmouseover and onmouseout

These two event classes will support you produce nice effects including photographs or even including text as well.

<html>
<head>
<script type = "text/js">
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
</head>
<body>
<div onmouseover = "over()" onmouseout = "out()">
</div>
</body>
</html>

14. JavaScript and Cookies

Cookies are small amount of data or plain text  files that is stored in a browser.  Cookie are user information of web page. Web Browsers and Servers utilize the HTTP method to communicate and HTTP is some stateless protocol. But how to keep users’ device knowledge over all these web pages.

  1. Create the cookie
  2. Read the stored cookie value
  3. Modify the cookie value
  4. Delete the cookie

Cookies are stored in a name value pair .

Username=”David”

1.Create the cookie:

Javascript cookies are created by document.cookie property.

document.cookie =” fname =David”

document.cookie =” lname =Selandar”

2.Read the stored cookie value

We  Can get all storied value in cookie of browser as:

document.cookie

It will how all cookie value as name vale pair.  Output will be

fname= David; lname= Selandar

Storing Cookies

The simplest method to produce a cookie is to select a strand value to this document. cookie object, which views like this.

<html>
<head>
<script type = "text/javascript">
function WriteCookieValue() { if( document.myform.customer.value == "" )
{ alert("Enter the value!"); return; }
cookievalue = escape(document.myform.customer.value) + ";";
document.cookie = "name=" + cookievalue; document.write
("SettingtheCookies : " + "name=" + cookievalue ); }
</head>
<body>
<form name = "myform" action = "">
<input type = "button" value = "SettheCookie" onclick = "WriteCookie();"/>
</form>
</body>
</html>
Reading Cookies

Reading a cookie is simply as simple as signing one because of this benefit of the document. So you can practice the string whenever you desire to access the cookie.

3.Modify the cookie value

We can modify the cookie value same way as create like:

document.cookie =” fname =Martin”

document.cookie =” lname =Walton”

4.Delete the cookie

We can delete the cookie through value as empty and expiry date as a past value

document.cookie = ” fname =; expires=Wed, 01 Jan 1940 00:00:00 UTC; path=/;”;

Sometimes you will need to delete a cookie so that after attempts to read the cookie results nothing.

<html>
<head>
<script type = "text/JS">
WriteCookieValue() {
now.setMonth( now.GetMonth() - 1 );
cookievalue = escape(document.customer.value) + ";"
}
</script>
</head>
<body>
<form name = "" action = "">
<input type = "button" value = "SettheCookieValue" onclick = "WritetheCookie()"/>
</form>
</body>
</html>

Setting Cookies Expiry Date

You can increase the life from a cookie behind the current browser assembly by placing an expiration date and keeping the expiry date inside the cookie.

How Does It Work?

Your server sends any data to that visitor’s browser in this form from a cookie. The browser may receive the cookie.

Expires − The date this cookie will expire. If this is blank, the cookie order expires when that visitor quits the browser.

Domain − The field title from your site.

Path − The path through that directory or web page that placed this cookie.

Secure − If this field contains that word “secure”, then the cookie may completely signify improved with a protected server.

Name=Value − Cookies expect set also regained in the formation of key-value pairs

15. JavaScript Page Redirection

You might have found a site where you agreed on a URL to open any page X though inside you stopped directed over extra page Y. It occurs due to page redirection. Refresh.

  • In such a scenario, you may require to read all your guests toward the new site. you can practice client-side side redirection to land your users toward that appropriate page.
  • The Search Engines may recognize already filed your pages. you would like to use your guests reaching through search engines.

How Page Re-direction Works?

There square measure a few of the way to direct to a different webpage with JavaScript.

  • If the domain owner not interested about name then change to new name. In such a situation, owner might be  want to direct all guests to the new domain. Here you’ll be able to maintain your recent domain however place one page domain with a page domain redirection specified all of your recent domain guests can return to your new domain.
  • If domain owner create multiple pages depends on the versions of browsers based on the various countries , then replace of of using page redirection use client-side page domain redirection to land site users on the suitable page.
  • The page which is used for search it is already indexed. But whereas moving to a different domain,owner wouldn’t feel to lose your guests by through coming  search engines. So owner can use client-side page domain redirection. But detain mind this could not done make fool the programmer, it may lead your website to urge illegal.
Example 1:

It is quite easy to do a surface redirect working JavaScript on the client side.To redirect your site visitors to a new page, you simply expect to compare each line within your front section as follows.

Program:
<html>
<head>
<script type = "text/javascript">
function Redirect()
{ window.location = "www.besanttech.com"; }
</script>
</head>
<body>
<p>Click the Button,Redirected to home page.</p>
<form>
<input type = "button" value = "redirectme" onclick = "Redirect();" />
</form>
</body>
</html>
Example 2:

You can show a suitable message on your situation visitors before redirecting them toward a different page. This would require a bit period delay to arrange a new page.

<html>
<head>
<script type = "text">
{ if( document.myform.customer.value == "" )
{ alert("Enter the Value!"); return; }
cookievalueset = escape(document.myform.customer.value) + ";"; 
document.cookie = "name=" + cookievalue; document.write 
("Setting the Value : " + "name=" + cookievalue ); }
</script>
</head>
<body>
<form name = "myform" action = "">
<input type = "button" value = "Set Cookie Value" onclick = "WriteCookie();"/>
</form>
</body>
</html>
Example 3:
<html>
<head>
<script type = "text">
var browsername = navigator.Name;
if( browsername == "Netscape" )
{ window.location = "http://www.besanttech.com"; }
else if ( browser=="Explore Browser")
{ window.location = "http://www.besanttech.com"; }
else { window.location = "http://www.besanttech.com"; }
</script>
</head>
<body>
</body>
</html>

16. JavaScript Document Object Model

In the browser every web page is consider as an object. It is an Application interface of HTML and XML documents. This is the logical structure of documents. Here XML is provide the data as documents, the DOM will processing and managing that data.

By using DOM, we can able to add, edit, modify, rearrange and delete the elements. This process is called DOM. Actually a web documents need an API for create structure, DOM provides it to the document.

All the DOM elements must follow the hierarchy flow. Every element is placed within parent element unless it is parent.

Example:
<h1>
<p>Document object Model </p>
</h1>

The hierarchy of this example will look like,

H1->   p  ->      innerHTML text

 The hierarchy is based on default objects, that is based on following objects

Window object:

First of hierarchy, it’s always in outer side of elements just like wrapping of elements.

Document object:

The object within the window object is called as document object. This is a content of the page.

Form object:

The object within the tag <form>…</form> is called as form objects. It is using to get the inputs from client and using to submit the data.

Form control elements:

Elements which contained by form tag is called as form control elements. Like text box, radio button, select kind of input elements hold by form tags.

17. Types of DOM:

DOM has so many types based on versions, JavaScript engines and browser. Some of them listed below.

Legacy DOM:

This is introduced in oldest version of JavaScript. But this now only used within form tags, in other portions need some access. This is compatible on all browsers.

The W3C DOM:

This is the standardized DOM by W3C. This one widely using now and give all access to modify all the DOM elements. And it will support by all browsers.

IE4 DOM:

This is compatible with Internet Explorer 4 and previous versions, recent days Edge or IE5 also supports the W3C DOM.

18. JavaScript – The Math Object

In JavaScript Math is an object, It contains properties and methods of mathematical properties like square root, rounded values and constants like Pi, Sin values. The properties contains in a Math object all are static and this is not a constructor. We can call the math as an object without creating it. Some of the properties or methods need one or more parameters.

Syntax:

Rules to write:

  1. “M” in Math must be in Caps
  2. Math object continue with Dot
Example:
var pi = Math.pi
var sqrt = Math.sqrt(4)

The output of previous line is square root of 4, i.e. 2

Properties in Math:

The properties in math will return some mathematical constants like Pi, values of cos, sin, Logarithmic values and so on.

Syntax to call properties:
Math. <PropertyName>
Examples:
  • To get Log values:
    • log2 (2) // To find logarithmic value
    • LOG2E // Base 2 Logarithm of E
    • LN10 // Natural algorithm of 10
  • To get Pi value
    • PI // Return PI constant 3.14
  • To get Euler’s constant
    • E //Return Euler’s constant 2.718
  • To get square root
    • SQRT1_2 //Return square root of ½ = 0.707
    • SQRT2 //Return square root of 2 = 1.414

Methods in Math:

In Math, Mathematical operations like square root, rounded numbers, minimum and maximum. Most of the methods in Math can hold parameter. So don’t forget to pass that.

Syntax to call methods:
Math. <MethodName>
Examples:
  • cos(<value>)        //Return the cosine value
  • log (<value>)       //Return the log value of base E number
  • max (value 1 , value 2, value 3) //Return maximum value
    • max(1,2,3) // Output is 3
  • min (value 1 , value 2, value 3) //Return minimum value
    • min (1,2,3) // Output is 1
  • sqrt(<value>) //Return square root of the value
    • sqrt(16) //Output is 4

19. JavaScript Regular Expressions and RegExp Object

JavaScript regular expressions is used to match the patterns of characters.

RegExp is defined as Regular Expression class. It is used to do

  • Pattern Matching
  • Search and replace functions
Syntax:

Syntax of RegExp looks like follows

var characterPattern = new RegExp (characterPattern , modifiers)

(Or)

var pattern = /characterPattern/modifiers;

  1. characterPattern – The specified character pattern to check expression.
  2. modifiers – Functionality of RegExp like globally specified, case-insensitive.

Modifiers:

Modifiers are used to do some operation with specified patterns.

  • i – Make case insensitive
  • g – Do global match
  • m – To do multiline match.
Example:
var characters = “try to Find this”
var pattern = /find/i;
var output = characters.match(pattern);
//  Output is” Find “

Brackets:

Brackets ([ ]) is used to find characters range.

  • [0-9] – Find the numbers within this range
  • [a-e] – Find the characters within range
Example:
var characters = “try to find this”
var pattern = /[a-f]/ig;               //Two modifiers in same syntax
var output = characters.match(pattern);
// Output is” f,d “

Quantifiers:

Quantifiers used to find the position and frequency of the mentioned character. The flags like +, ? and * are using as flags in quantifiers.

Example:
var characters = “haaai aam fiine”
var pattern = /a+/ig;                  //Two modifiers in same syntax
var output = characters.match(pattern);
// Output is” aaa,aa “

20. JavaScript Error and Exception Handling

Not only in JavaScript, have every applications needed error and exception handling.

ERROR:

Error – incorrect, in programming or JavaScript the problem caused in application because of not handling that. The error will make the application stop. Actually application can able to try the catch to run it. If not error will occur.

There are three types of error. They are

  • Syntax error
  • Logical error
  • Runtime error

Syntax error:

Syntax error will identify during the time of compiling in old languages but in JavaScript it will occurred in interpret time. It is also called as Parsing Errors.

For example in JavaScript,

document.getElementById(“demo”

In the above JS statement has an error in syntax, one closing bracket is missed. This is called as Syntax error.

Logical error:

The result of logical error completely in the hands of developer. If suppose any logic of code is missing or data mishandling or based on numbers this error will occur.

The output of the application will end in unrelated because of this error. There is no catch for this error. So developer have to design the project carefully and flawless.

Runtime error:

Runtime error occurred during execution, not in compiler. It will affect the whole thread of JavaScript. If this error had occurred it will stop the other functionalities of JavaScript which next to that error function.

Example:

In JavaScript,

var string_1 = “haii”;
string_1.round();
In the above JavaScript Statement try to call the method which is not exist. It will lead to runtime error. It is also called as Exceptions.

EXCEPTIONS HANDLING:

In latest version of JavaScript have exception handling, by using that we can handle errors and exception handlings.

Try…Catch…Finally and Throw Statement:

Syntax:
try     {
//  When code executes successfully
}
catch         {
//  When exceptions occurred o
}
[finally {
// When exception occurred do this
}

21. JavaScript Form Validation

JavaScript helps to ensure that form field values in client-side itself. It just loops all the fields and checks the data as per the required format.

HTML:-

<form name="sample" action="url.php" onsubmit="formvalidation()" >
Email: <input type="text" name="email"  onblur="validateEmail(this);"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="Login ">
</form>

Script:-

function formvalidation() { // This function will calls on click of loginvar name = document.sample.email.value;
var password = document.sample.password.value;
if (name == null || name == "") {
alert("Name can't be blank");
return false;
} else if (password.length < 8) {
alert("Password must be at least 8 characters long.");
return false;
}
}
function validateEmail(emailField) {   // Email validation happen onblur event
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(emailField.value) == false) {
alert('Invalid Email Address');
return false;
}
return true;
}

Email addresses should always have the same structure: sometext@webdomain.extention

Generally Server-side checking entails the user submitting the form to the server, such as ASP, C# or PHP, then the server code checks and returns an error if it finds one. This would takes time and also costly too, which hits server each time even for small validation.

Client-side validation means, JavaScript intercepting the form before it’s submitted to check for error using regex, it reduces the number server requests.

“required” is keyword we can include in our html field elements to make sure that value must. If the required fields are empty it will throw eror immediately on browser itself.

checkValidity() is the method used for checking fields have valid values. If at least one value is invalid then it will fails.

Sample:
var form = documents.getElementbyId('sample');
form.checkvalidity();

It returns Boolean values, if the form valid then true else false.

22. JavaScript Animation

Animation handling do by Dom elements manipulation with their styles around the page. It also be make it happen events and timers.,

An animation can be implemented as a sequence of frames – usually small changes to HTML/CSS properties. Timing function, like CSS-property transition-timing-function that gets the fraction of time that passed and returns the animation completion. If animation goes on uniformly with the same speed, means that it maintains linear action.

JavaScript animations should be implemented via requestAnimationFrame. That built-in method allows to setup a callback function to run when the browser will be preparing a react.

Animating with setInterval

Html:

<p id="instruct"><button>
click to start the animation
</button>
</p>

script:

function animLoop( render, element ) {var running, lastFrame = +new Date,
raf = window.mozRequestAnimationFrame    ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame     ||
window.oRequestAnimationFrame;
function loop( now ) {
// stop the loop if render returned false
if ( running !== false ) {
raf( loop, element );
var deltaT = now - lastFrame;
if ( deltaT < 160 ) {
running = render( deltaT );
}
lastFrame = now;}
}
loop( lastFrame );
}
var elems = [],
instruct = document.getElementById( "instruct" );
instruct.onclick = function() {
if ( !elems.length ) {
instruct.innerHTML = "Switching between tabs won't create any wormhole.";
animLoop(function( deltaT ) {
var i,
elem;
elem = document.createElement( "div" );
document.body.appendChild( elem );
elems.push( [ elem, 0 ] );
i = elems.length;
while ( i-- ) {
elems[i][0].style.left = ( elems[i][1] += 10 * deltaT / 50 ) + "px";
if ( elems[i][1] > 400 ) {
document.body.removeChild( elems[i][0] );
elems.splice( i, 1 );
}
}
});
}
};

Using css

With help of css also we can achieve basic animations with transform and transition properties

Html:

<h3>Pure Javascript</h3><div class="zoomPic"></div>
<button class='zoom'>Zoom</button>
<button class='pause'>Pause</button>
<button class='zoomout'>Zoom Out</button>
<h3>jQuery</h3>
<div class='zoomPic'></div>
<button class='zoom'>Zoom</button>
<button class='pause'>Pause</button>
<button class='zoomout'>Zoom Out</button>

CSS:

.zoomPic {
margin: 30px;
width: 300px;
height: 180px;
background-color: blue;
background-image: url(http://placehold.it/1200x720);
background-repeat:no-repeat;
background-position:50% 50%;
background-size: 300px 180px;
-webkit-transition: all 2.5s ease-in-out;
-moz-transition: all 2.5s ease-in-out;
-ms-transition: all 2.5s ease-in-out;
-o-transition: all 2.5s ease-in-out;
transition: all 2.5s ease-in-out;
}
.zoomPic.zoom {
background-size: 1200px 720px !important;
}

Script:

var zoomOne = document.getElementsByClassName('zoomPic')[0],
zoomOneBGSize = window.getComputedStyle(zoomOne).getPropertyValue('background-size'),
$zoomTwo = $('.zoomPic:eq(1)'),
zoomTwoBGSize = $zoomTwo.css('background-size');
document.getElementsByClassName('zoom')[0].onclick = function() {
if(!zoomOne.classList.contains('zoom'))
{
zoomOne.classList.add('zoom');
}
}
document.getElementsByClassName('pause')[0].onclick = function() {
var computedStyle = window.getComputedStyle(zoomOne),
backgroundSize = computedStyle.getPropertyValue('background-size');
zoomOne.style.backgroundSize = backgroundSize;
zoomOne.classList.remove('zoom');
}
document.getElementsByClassName('zoomout')[0].onclick = function() {
zoomOne.classList.remove('zoom');
zoomOne.style.backgroundSize = zoomOneBGSize;
}

23. JavaScript Multimedia

Multimedia comes in many different formats, it can be text, videos, music, sound animations and much more.

various video formats:

  1. MP4 (mp4, m4a, m4v, f4v, f4a, m4b, m4r, f4b, mov)
  2. 3GP (3gp, 3gp2, 3g2, 3gpp, 3gpp2)
  3. OGG (ogg, oga, ogv, ogx)
  4. WMV (wmv, wma, asf*)
  5. WEBM (webm)
  6. FLV (flv)
  7. AVI*
  8. QuickTime*
sample:
<script>
var sound = new Howl({
src: ['src path']
volume: 0.5,
onend: function () {
alert('Finished!');
}
});
sound.play()
</script>

24. Javascript Debugging

Javascript code does not show any error in browser, if any mistakes happened in code. It just prints error in browser console and loads html as it is.

To do debug js code, we may some keywords like console.log(), alert(), document.write() and debugger., All those methods helps us to find value coming as expected. And these has been supported by all latest browsers.

Console.log

console.log is the efficient way to debug errors, it sets a breakpoint in better way. It stops execution of code and values can be examined.

To see this result, enter into developer tool area by pressing F12 or right chick inspect element. Then Go to source, select JavaScript and set breakpoint, if control reach that point then event listener stops the execution flow.

var x = 10;
console.log(x); // It prints value in  console

alert

The alert displays popup message to the user, which have only ok button. It displays all data type values without any conversation. It acts as a breapoint to check the control flow.

var y = 20;
alert(y);  // It shows alert popup on top the screen

document.write

document.write() statement directly reads document stream in HTML structure and update values into it.

The disadvantages of using this method, it won’t give friendly environment to debug, because of updating document value it overwrites existing whole document value.

var text = “Welcome to screen”;
document.write(text); //It updates value directly in document, display in screen

debugger

The debugger keyword also used to stop the execution of the code, and calls debugging function without settings any breakpoint. For this developer tool needs to be open else this statement has no effect.

debugger; // It acts as a breakpoint, in stops the code execution if console window opens in browser

25. JavaScript Image Map

Img: The “img” tag is used to display the image what you want like world map, science, zoological etc. Suppose we want to navigate the particular part of the image like city, state, parts of body etc. then you can used the “<map> and <area>” HTML tags.

map: The “map” and “area” tag are used to coordinate the part of the area. The <map> element creates the map of the <img>.  The map tag have only one attribute “name”. It point from the img tag using usemap attribute.

area: The “area” tag specifying the shape and the coordinates that define a borders. The area tag contain ploy, rect, and circle.

Example:
<html>
<head>
<title>Elephant Parts Using Image Map</title>
<script type="text/javascript">
function show_parts(value)
{
document.getElementById("parts").innerHTML = value;
}
</script>
<style>
#parts{height:50px; font-size:20px; color:red;}
</style>
</head>
<body>
<h1>Elephant Parts using Image Map</h1>
<p>Please move the cursor to over the body of the elephant.</p>
<div id = "parts">
</div>
<img src="https://easydrawingguides-7512.kxcdn.com/wp-content/uploads/2016/11/how-to-draw-an-elephant-20.png" usemap="#image-map">
<map name="image-map">
<area target="_blank" alt="Front Leg" title="Front Leg" href="Front Leg" coords="227,227,242,266,234,304,237,333,245,360,242,377,254,382,271,378,278,379,279,390,295,394,316,395,335,390,343,384,335,354,342,326,349,301,353,273,351,244,345,205" shape="poly" onMouseOver="show_parts('It is a elephant Leg')" onMouseOut="show_parts('')">
<area target="_blank" alt="Back leg" title="Back leg" href="Back leg" coords="435,297,452,357,445,359,448,372,460,374,470,375,476,383,495,390,538,387,556,379,544,343,545,301,548,254,558,203,558,172,532,159,506,150,476,153,457,199,453,284" shape="poly" onMouseOver="show_parts('It is a elephant Leg')" onMouseOut="show_parts('')">
<area target="_blank" alt="tusk" title="tusk" href="tusk" coords="159,214,146,220,124,213,94,205,77,194,68,183,94,186,120,190,147,193,156,192" shape="poly" onMouseOver="show_parts('It is a elephant Tusk')" onMouseOut="show_parts('')">
<area target="_blank" alt="ear" title="ear" href="ear" coords="239,83,243,71,255,55,274,43,305,27,305,68,311,110,315,152,306,180,295,210,277,207,261,187,253,179" shape="poly" onMouseOver="show_parts('It is a elephant Ear')" onMouseOut="show_parts('')">
<area target="_blank" alt="praise" title="praise" href="praise" coords="86,210,83,229,80,268,83,298,91,324,104,341,120,356,145,362,165,359,182,345,189,325,156,342,125,324,114,272,121,243,134,218" shape="poly" onMouseOver="show_parts('It is a elephant Praise')" onMouseOut="show_parts('')">
<area target="" alt="tail" title="tail" href="tail" coords="563,238,574,258,588,275,589,305,592,323,586,342,591,369,610,377,611,358,612,337,601,308,602,282,593,255,564,196" shape="poly" onMouseOver="show_parts('It is a elephant Tail')" onMouseOut="show_parts('')">
</map>
</body>
</html>
Output:

image map

26. JavaScript – Browsers Compatibility

Browser Compatibility is the capacity of our webapp to functioning across the varying browsers and low level version browsers.

Why we need check browser compatibility. Because of different browsers reading the website code in different methods. So browser is important to confirmed that our website is compatible across different browsers. Because of all user not using the same browser. The major browsers to confirming your web site is compatible for IE, Chrome, Mozilla Firefox, Opera, Mac Safari and mobile devices like iphone, android, tab, notepad etc.

Navigator

Especially the Navigator is identified which browser we used. It can be used to get the information about browser like user agent, appname, appCodeName etc.

Syntax:

Navigator.Property_name.

Property names:

The Navigator’s different properties that we can use in our web page. Properties are listed below.

appCodeName: It returns the internal code name of the current browser.

appName: It returns the official  name of the current browser.

appVersion: It returns the version of the browser.

connection: It returns the information about the network.

language: It return the languages known to the user.

mimeTypes: It returns the MIME types supported by the browser.

userAgent: It returns the user agent string of the current browser.

Methods:

javaEnabled: It returns a boolean indicator (true/false) whether the browser is Java-enabled or not.

Example:
<html>
<head>
<title>Browser Identification</title>
</head>
<body>
<script>
var ua = navigator.userAgent.toLowerCase();
if(ua.indexOf('opera')>=0){
alert("Is a opera browser");
}else if(ua.indexOf('msie')>=0){
alert("Is a MSIE browser");
}else if(ua.indexOf('chrome')>=0){
alert("Is a Chrome browser");
}else{
alert("Is a Unknown browser");
}
</script>
</body>
</html>
Output:

Browsers Compatibility

27. JavaScript Built-in Functions and Objects

JavaScript has more than five built-in functions are there. They are eval, parseInt, parseFloat, escape and unescape

eval:

It evaluate a string and returns a value not a string.

Format:

eval(expression)

Example:
var a1 = 123;
var a2 = 423;
var b1 = "343";
document.write(eval("a1 + a2 + 2"));
output: 548
document.write(eval(b1));
output: 343

parseInt:

It analyse a string parameter(argument) and returns a integer of the specific radius or base.

Format:
parseInt(string)
parseInt(string, radius)
Example:
parseInt("F", 16)
output:  15
parseInt("17", 8)
output:  15
parseInt("Hello", 8)
output:  NaN

parseFloat:

Analyse a string parameter(argument) and returns a floating value.

Format:
parseFloat(string)
Example:
parseFloat("312.14")
output: 312.14
parseFloat("314e-2")
output: 3.14

escape:

It returns a hexadecimal value of an argument in the ISO Latin-1 char.

Format:
escape(string)
Example:
escape("xyz&%")
output: xyz%26%25

unescape:

It returns a ASCII value from the specified value.

Format:
unescape(string)
Example:
unescape("%26")
output:  &

The JavaScript contain lot of built-in objects are there. It used to simplifying the codes. They are

  • String Functions
  • Array Functions
  • Date Functions
  • Math Functions

String Functions

indexOf():- It returns the position from the calling string of the first occurrence of the specified value.

lastIndexOf():- It return the position from the calling string of the last occurrence of the specified value.

length():- It returns the length of the specific string.

replace():- It replaces the match of the finding string in a specific string.

split():- It splitting a string value into an array of value by separate by character by character.

Array Function

concat():- It returns the new array joined with a collection of arrays.

filter():- It returns to create a new array with all of its element of this array which filter return true.

indexOf():- It return the position or index of an first find of the array. It return -1 if no result found.

pop():-  It removes the last element from the specific array and return it.

shift():- It removes the first element from the specific array and return it.

Date Function

Date():-  It returns the system date.

getHours():- It return the current hours from the system date.

getMonth():- It return the current month from the system date.

getYear():-  It return the current year from the system date.

getMinutes():-It return the current minute from the system date.

Math Function

abs():-  It returns a absolute value of a specified number

floor():- It returns a largest integer less than or equal to a specific value.

max():- It returns a maximum of a number from the set of numbers.

min():-  It returns a minimum of a number from the set of numbers.

random():-  It returns a random number within 0 and 1.

Leave a Reply

Your email address will not be published. Required fields are marked *

Looking for Online Training