0% found this document useful (0 votes)
134 views94 pages

AWP Lab Manual

The document discusses Cascading Style Sheets (CSS) and provides an overview of CSS including: - CSS is used to design HTML tags and widely used on the web. - CSS allows adding style to HTML documents and changing website looks with few code changes. - CSS solves problems of repeating styles, saves time by changing styles in one file, and provides more attributes than HTML.

Uploaded by

SAVALIYA FENNY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
134 views94 pages

AWP Lab Manual

The document discusses Cascading Style Sheets (CSS) and provides an overview of CSS including: - CSS is used to design HTML tags and widely used on the web. - CSS allows adding style to HTML documents and changing website looks with few code changes. - CSS solves problems of repeating styles, saves time by changing styles in one file, and provides more attributes than HTML.

Uploaded by

SAVALIYA FENNY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 94

Cascading Style Sheet.

Practical No: __________ Date: __________


Aim: Study of basic implementation with Cascading Style Sheet.

Theory
CSS tutorial or CSS 3 tutorial provides basic and advanced concepts of CSS technology.
Our CSS tutorial is developed for beginners and professionals. The major points of CSS are
given below:
 CSS stands for Cascading Style Sheet.
 CSS is used to design HTML tags.
 CSS is a widely used language on the web.
 HTML, CSS and JavaScript are used for web designing. It helps the web designers to
apply style on HTML tags.
What is CSS?
CSS stands for Cascading Style Sheets. It is a style sheet language which is used to describe
the look and formatting of a document written in markup language. It provides an additional
feature to HTML. It is generally used with HTML to change the style of web pages and user
interfaces. It can also be used with any kind of XML documents including plain XML, SVG
and XUL.
CSS is used along with HTML and JavaScript in most websites to create user interfaces for
web applications and user interfaces for many mobile applications.
What does CSS DO?
 You can add new looks to your old HTML documents.
 You can completely change the look of your website with only a few changes in CSS
code.

Why use CSS


These are the three major benefits of CSS:

1) Solves a big problem


Before CSS, tags like font, color, background style, element alignments, border and size had
to be repeated on every web page. This was a very long process. For example: If you are
developing a large website where fonts and color information are added on every single page,
it will be become a long and expensive process. CSS was created to solve this problem. It
was a W3C recommendation.

2) Saves a lot of time


CSS style definitions are saved in external CSS files so it is possible to change the entire
website by changing just one file.

3) Provide more attributes


CSS provides more detailed attributes than plain HTML to define the look and feel of the
website.

Gandhinagar Institute of Technology 3161611 AWP


 CSS Syntax:

A CSS rule set contains a selector and a declaration block.

Fig 1: CSS Syntax.


Selector: Selector indicates the HTML element you want to style. It could be any tag like
<h1>, <title> etc.
Declaration Block: The declaration block can contain one or more declarations separated by
a semicolon. For the above example, there are two declarations:
1. color: yellow;
2. font-size: 11 px;
Each declaration contains a property name and value, separated by a colon.
Property: A Property is a type of attribute of HTML element. It could be color, border etc.
Value: Values are assigned to CSS properties. In the above example, value "yellow" is
assigned to color property.
1. Selector{Property1: value1; Property2: value2; ..........;}

 CSS Selector

CSS selectors are used to select the content you want to style. Selectors are the part of CSS
rule set. CSS selectors select HTML elements according to its id, class, type, attribute etc.
There are several different types of selectors in CSS.
1. CSS Element Selector
2. CSS Id Selector
3. CSS Class Selector
4. CSS Universal Selector
5. CSS Group Selector

 CSS Element Selector


Example:
<!DOCTYPE html>
<html>

Gandhinagar Institute of Technology 3161611 AWP


<head>
<style>
p{
text-align: center;
color: blue;
}
</style>
</head>
<body>
<p>This style will be applied on every paragraph.</p>
<p id="para1">Me too!</p>
<p>And me!</p>
</body>
</html>
Output:
This style will be applied on every paragraph.
Me too!
And me!

 CSS Id Selector

The id selector selects the id attribute of an HTML element to select a specific element. An id
is always unique within the page so it is chosen to select a single, unique element.

It is written with the hash character (#), followed by the id of the element.

Let’s take an example with the id "para1".


Example:
<!DOCTYPE html>
<html>
<head>
<style>
#para1 {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<p id="para1">Hello Javatpoint.com</p>
<p>This paragraph will not be affected.</p>
</body>
</html>
Output:
Hello Javatpoint.com
Gandhinagar Institute of Technology 3161611 AWP
 CSS Class Selector
The class selector selects HTML elements with a specific class attribute. It is used with a
period character. (Full stop symbol) followed by the class name.

Note: A class name should not be started with a number.


Let's take an example with a class "center".
Example:
<!DOCTYPE html>
<html>
<head>
<style>
.center {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1 class="center">This heading is blue and center-aligned.</h1>
<p class="center">This paragraph is blue and center-aligned.</p>
</body>
</html>
Output:

This heading is blue and center-aligned.


This paragraph is blue and center-aligned.

 CSS Universal Selector


Example:
<!DOCTYPE html>
<html>
<head>
<style>
*{
color: green;
font-size: 20px;
}
</style>
</head>
<body>
<h2>This is heading</h2>
<p>This style will be applied on every paragraph.</p>
<p id="para1">Me too!</p>
<p>And me!</p>
</body>
</html>
Gandhinagar Institute of Technology 3161611 AWP
Output: This is heading
This style will be applied on every paragraph.
Me too!
And me!
 CSS Group Selector
The grouping selector is used to select all the elements with the same style definitions.
Grouping selector is used to minimize the code. Commas are used to separate each selector in
grouping.
Let's see the CSS code without group selector.
h1 {
text-align: center;
color: blue;
}
h2 {
text-align: center;
color: blue;
}
p{
text-align: center;
color: blue;
}

As you can see, you need to define CSS properties for all the elements. It can be grouped in
following ways:
h1,h2,p {
text-align: center;
color: blue;
}

Let's see the full example of CSS group selector.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, p {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1>Hello Javatpoint.com</h1>
<h2>Hello Javatpoint.com (In smaller font)</h2>
Gandhinagar Institute of Technology 3161611 AWP
<p>This is a paragraph.</p>
</body>
</html>
Output:

Hello Javatpoint.com

Hello Javatpoint.com (In smaller font)


This is a paragraph.
 How to add CSS

CSS is added to HTML pages to format the document according to information in the style
sheet. There are three ways to insert CSS in HTML documents.
1. Inline CSS
2. Internal CSS
3. External CSS

 Inline CSS
Inline CSS is used to apply CSS on a single line or element.
For example:
1. <p style="color:blue">Hello CSS</p>

We can apply CSS in a single element by inline CSS technique.

The inline CSS is also a method to insert style sheets in HTML document. This method
mitigates some advantages of style sheets so it is advised to use this method sparingly.

If you want to use inline CSS, you should use the style attribute to the relevant tag.

Syntax:

<htmltag style="cssproperty1:value; cssproperty2:value;"> </htmltag>

Example:

<h2 style="color:red;margin-left:40px;">Inline CSS is applied on this heading.</h2>


<p>This paragraph is not affected.</p>

Output:

Inline CSS is applied on this heading.


This paragraph is not affected.

 Disadvantages of Inline CSS

Gandhinagar Institute of Technology 3161611 AWP


 You cannot use quotations within inline CSS. If you use quotations the browser will
interpret this as an end of your style value.
 These styles cannot be reused anywhere else.
 These styles are tough to be edited because they are not stored at a single place.
 It is not possible to style pseudo-codes and pseudo-classes with inline CSS.
 Inline CSS does not provide browser cache advantages.

 Internal CSS

Internal CSS is used to apply CSS on a single document or page. It can affect all the elements
of the page. It is written inside the style tag within head section of html.

Example:
<style>
p{color:blue}
</style>

 External CSS
External CSS is used to apply CSS on multiple pages or all pages. Here, we write all the CSS
code in a css file. Its extension must be .css for example style.css.
Example:
1. p{color:blue}
You need to link this style.css file to your html pages like this:
1. <link rel="stylesheet" type="text/css" href="style.css">
The link tag must be used inside head section of html.

The external style sheet is generally used when you want to make changes on multiple pages.
It is ideal for this condition because it facilitates you to change the look of the entire web site
by changing just one file.

It uses the <link> tag on every pages and the <link> tag should be put inside the head section.
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>

The external style sheet may be written in any text editor but must be saved with a .css
extension. This file should not contain HTML elements.

Let's take an example of a style sheet file named "mystyle.css".

File: mystyle.css
body {
background-color: lightblue;
}

Gandhinagar Institute of Technology 3161611 AWP


h1 {
color: navy;
margin-left: 20px;
}

Note: You should not use a space between the property value and the unit. For example: It
should be margin-left: 20px not margin-left: 20 px.

Exercise:
1. Write CSS script for scroll value of the background-attachment property, which is the
default behavior. So when the page is scrolled, the background scrolls with it.
2. Write CSS script for the border of the paragraph elements with the image. In the first
paragraph, we are specifying the single value (i.e., round) of the border-image-repeat
property, whereas in the second paragraph, we are specifying two values (round,
stretch) of it, the first value for the horizontal sides and second value for the vertical
sides.

Review Questions:
1. What are the CSS frameworks?
2. Why background and color are the separate properties if they should always be set
together?
3. What is the use of ruleset?

Gandhinagar Institute of Technology 3161611 AWP


Java script
Practical No: __________ Date: __________

Aim: Understand basics of Java script syntax.


Theory

JavaScript can be implemented using JavaScript statements that are placed within
the <script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within your web page,
but it is normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags
as a script. A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
The script tag takes two important attributes −
 Language − this attribute specifies what scripting language you are using. Typically,
its value will be JavaScript. Although recent versions of HTML (and XHTML, its
successor) have phased out the use of this attribute.
 Type − this attribute is what is now recommended to indicate the scripting language in
use and its value should be set to "text/javascript".
 So your JavaScript segment will look like −
 <script language = "javascript" type = "text/javascript">
 JavaScript code
 </script>
 Your First JavaScript Code
 Let us take a sample example to print out "Hello World". We added an optional HTML
comment that surrounds our JavaScript code. This is to save our code from a browser
that does not support JavaScript. The comment ends with a "//-->". Here "//" signifies
a comment in JavaScript, so we add that to prevent a browser from reading the end of
the HTML comment as a piece of JavaScript code. Next, we call a
function document.write which writes a string into our HTML document.
 This function can be used to write text, HTML, or both. Take a look at the following
code.
Example:
<html>
<body>
<script language = "javascript" type = "text/javascript">

Gandhinagar Institute of Technology 3161611 AWP


<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>

Semicolons are Optional


Simple statements in JavaScript are generally followed by a semicolon character, just as they
are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if each of
your statements are placed on a separate line. For example, the following code could be written
without semicolons.
<script language = "javascript" type = "text/javascript">
<!--
var1 = 10
var2 = 20
//-->
</script>
But when formatted in a single line as follows, you must use semicolons −
<script language = "javascript" type = "text/javascript">
<!--
var1 = 10; var2 = 20;
//-->
</script>
Note − It is a good programming practice to use semicolons.

 Case Sensitivity
JavaScript is a case-sensitive language. This means that the language keywords, variables,
function names, and any other identifiers must always be typed with a consistent capitalization
of letters.
So the identifiers Time and TIME will convey different meanings in JavaScript.
NOTE − Care should be taken while writing variable and function names in JavaScript.

 Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −

Gandhinagar Institute of Technology 3161611 AWP


 Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript.
 Any text between the characters /* and */ is treated as a comment. This may span
multiple lines.
 JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript
treats this as a single-line comment, just as it does the // comment.
 The HTML comment closing sequence --> is not recognized by JavaScript so it should
be written as //-->.
 The following example shows how to use comments in JavaScript.
Example:
<script language = "javascript" type = "text/javascript">
<!--
// This is a comment. It is similar to comments in C++
/*
* This is a multi-line comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>

JavaScript Data types:


One of the most fundamental characteristics of a programming language is the set of data
types it supports. These are the type of values that can be represented and manipulated in a
programming language.
JavaScript allows you to work with three primitive data types −
 Numbers, e.g. 123, 120.50 etc.
 Strings of text e.g. "This text string" etc.
 Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only
a single value. In addition to these primitive data types, JavaScript supports a composite data
type known as object. We will cover objects in detail in a separate chapter.
Note − JavaScript does not make a distinction between integer values and floating-point
values. All numbers in JavaScript are represented as floating-point values. JavaScript
represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.

JavaScript Variables

Gandhinagar Institute of Technology 3161611 AWP


Like many other programming languages, JavaScript has variables. Variables can be thought
of as named containers. You can place data into these containers and then refer to the data
simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared
with the var keyword as follows.
<script type = "text/javascript">
<!--
var money;
var name;
//-->
</script>
You can also declare multiple variables with the same var keyword as follows –
<script type = "text/javascript">
<!--
var money, name;
//-->
</script>
Storing a value in a variable is called variable initialization. You can do variable initialization
at the time of variable creation or at a later point in time when you need that variable.
For instance, you might create a variable named money and assign the value 2000.50 to it
later. For another variable, you can assign a value at the time of initialization as follows.
Example:
<script type = "text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
Note − Use the var keyword only for declaration or initialization, once for the life of any
variable name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any
data type. Unlike many other languages, you don't have to tell JavaScript during variable
declaration what type of value the variable will hold. The value type of a variable can change
during the execution of a program and JavaScript takes care of it automatically.

Gandhinagar Institute of Technology 3161611 AWP


What is an Operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’
is called the operator. JavaScript supports the following types of operators.

Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Arithmetic Operators: JavaScript supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then –
Table 1: Arithmetic Operators

1
+ (Addition)
Adds two operands
Ex: A + B will give 30

2
- (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10

3
* (Multiplication)
Multiply both operands
Ex: A * B will give 200

4
/ (Division)
Divide the numerator by the denominator
Ex: B / A will give 2

5
% (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0

6
++ (Increment)
Increases an integer value by one
Ex: A++ will give 11

Gandhinagar Institute of Technology 3161611 AWP


7
-- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9

Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give
"a10"

Comparison Operators:

JavaScript supports the following comparison operators −


Assume variable A holds 10 and variable B holds 20, then –
Table 2: Comparison Operators

1
= = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition becomes
true.
Ex: (A == B) is not true.

2
!= (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal, then the
condition becomes true.
Ex: (A != B) is true.

3
> (Greater than)
Checks if the value of the left operand is greater than the value of the right operand, if
yes, then the condition becomes true.
Ex: (A > B) is not true.

4
< (Less than)
Checks if the value of the left operand is less than the value of the right operand, if yes,
then the condition becomes true.
Ex: (A < B) is true.

5
>= (Greater than or Equal to)

Gandhinagar Institute of Technology 3161611 AWP


Checks if the value of the left operand is greater than or equal to the value of the right
operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.

6
<= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of the right
operand, if yes, then the condition becomes true. Ex: (A <= B) is true.

 Logical Operators:

JavaScript supports the following logical operators −


Assume variable A holds 10 and variable B holds 20, then –

Table 3: Logical Operators

1
&& (Logical AND)
If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.

2
|| (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.

3
! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical NOT
operator will make it false.
Ex: ! (A && B) is false.

 Bitwise Operators:

JavaScript supports the following bitwise operators −


Assume variable A holds 2 and variable B holds 3, then –

Gandhinagar Institute of Technology 3161611 AWP


Table 4: Bitwise Operators

1
& (Bitwise AND)
It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.

2
| (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.

3
^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer arguments.
Exclusive OR means that either operand one is true or operand two is true, but not both.
Ex: (A ^ B) is 1.

4
~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
Ex: (~B) is -4.

5
<< (Left Shift)
It moves all the bits in its first operand to the left by the number of places specified in the
second operand. New bits are filled with zeros. Shifting a value left by one position is
equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4,
and so on.
Ex: (A << 1) is 4.

6
>> (Right Shift)
Binary Right Shift Operator. The left operand’s value is moved right by the number of
bits specified by the right operand. Ex: (A >> 1) is 1.

7
>>> (Right shift with Zero)
This operator is just like the >> operator, except that the bits shifted in on the left are
always zero. Ex: (A >>> 1) is 1.

Gandhinagar Institute of Technology 3161611 AWP


 Assignment Operators:

JavaScript supports the following assignment operators


Table 5: Assignment Operators

1
= (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C

2
+= (Add and Assignment)
It adds the right operand to the left operand and assigns the result to the left operand.
Ex: C += A is equivalent to C = C + A

3
−= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the result to the left
operand.
Ex: C -= A is equivalent to C = C - A

4
*= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the result to the left
operand.
Ex: C *= A is equivalent to C = C * A

5
/= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result to the left operand.
Ex: C /= A is equivalent to C = C / A

6
%= (Modules and Assignment)
It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A

Note − same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=,
|= and ^=.

Gandhinagar Institute of Technology 3161611 AWP


 Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then
executes one of the two given statements depending upon the result of the evaluation.

? : (Conditional )
If Condition is true? Then value X : Otherwise value Y

 typeof Operator:

The type of operator is a unary operator that is placed before its single operand, which can be
of any type. Its value is a string indicating the data type of the operand.
The type of operator evaluates to "number", "string", or "Boolean" if its operand is a number,
string, or Boolean value and returns true or false based on the evaluation.
Table 6: Return values for the type of Operator

Type String Returned by typeof

Number "number"

String "string"

Boolean "boolean"

Object "object"

Function "function"

Undefined "undefined"

Null "object"
 JavaScript - if...else Statement
 if statement
 if...else statement
 if...else if... statement.

 if statement
The if statement is the fundamental control statement that allows JavaScript to make decisions
and execute statements conditionally.

Syntax:
The syntax for a basic if statement is as follows −
if (expression) {
Statement(s) to be executed if expression is true
}
Gandhinagar Institute of Technology 3161611 AWP
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s)
are executed. If the expression is false, then no statement would be not executed. Most of the
times, you will use comparison operators while making decisions.

 if...else statement
The 'if...else' statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.

Syntax:
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s)
in the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else
block are executed.

 if...else if... statement


The if...else if... statement is an advanced form of if…else that allows JavaScript to make a
correct decision out of several conditions.

Syntax:
The syntax of an if-else-if statement is as follows −
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where each if is a
part of the else clause of the previous statement. Statement(s) are executed based on the true
condition, if none of the conditions is true, then the else block is executed.
JavaScript for...in loop
The for...in loop is used to loop through an object's properties. As we have not discussed
Objects yet, you may not feel comfortable with this loop. But once you understand how objects
behave in JavaScript, you will find this loop very useful.

Syntax:
The syntax of ‘for..in’ loop is −
for (variablename in object) {
Gandhinagar Institute of Technology 3161611 AWP
statement or block to execute
}
In each iteration, one property from object is assigned to variablename and this loop
continues till all the properties of the object are exhausted.

Example:
Try the following example to implement ‘for-in’ loop. It prints the web
browser’s Navigator object.
<html>
<body>
<script type = "text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator) {
document.write(aProperty);
document.write("<br />");
}
document.write ("Exiting from the loop!");
//-->
</script>
<p>Set the variable to different object and then try...</p>
</body>
</html>
 JavaScript - Loop Control:
JavaScript provides full control to handle loops and switch statements. There may be a
situation when you need to come out of a loop without reaching its bottom. There may also
be a situation when you want to skip a part of your code block and start the next iteration of
the loop.
To handle all such situations, JavaScript provides break and continue statements. These
statements are used to immediately come out of any loop or to start the next iteration of any
loop respectively.

 The break Statement


The break statement, which was briefly introduced with the switch statement, is used to exit
a loop early, breaking out of the enclosing curly braces.

 The continue Statement


The continue statement tells the interpreter to immediately start the next iteration of the loop
and skip the remaining code block. When a continue statement is encountered, the program
flow moves to the loop check expression immediately and if the condition remains true, then
it starts the next iteration, otherwise the control comes out of the loop.

Gandhinagar Institute of Technology 3161611 AWP


 JavaScript – Functions:
A function is a group of reusable code which can be called anywhere in your program. This
eliminates the need of writing the same code again and again. It helps programmers in writing
modular codes. Functions allow a programmer to divide a big program into a number of small
and manageable functions.
Like any other advanced programming language, JavaScript also supports all the features
necessary to write modular code using functions. You must have seen functions
like alert() and write() in the earlier chapters. We were using these functions again and again,
but they had been written in core JavaScript only once.
JavaScript allows us to write our own functions as well. This section explains how to write
your own functions in JavaScript.

 Function Definition
Before we use a function, we need to define it. The most common way to define a function in
JavaScript is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.

Syntax:
The basic syntax is shown here.
<script type = "text/javascript">
<!--
function functionname(parameter-list) {
statements
}
//-->
</script>

Example:
Try the following example. It defines a function called sayHello that takes no parameters –
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello there");
}
//-->
</script>

Calling a Function:
To invoke a function somewhere later in the script, you would simply need to write the name
of that function as shown in the following code.

Gandhinagar Institute of Technology 3161611 AWP


Example:
<html>
<head>
<script type = "text/javascript">
function sayHello() {
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>

Function Parameters:
Till now, we have seen functions without parameters. But there is a facility to pass different
parameters while calling a function. These passed parameters can be captured inside the
function and any manipulation can be done over those parameters. A function can take
multiple parameters separated by comma.

Example:
Try the following example. We have modified our sayHello function here. Now it takes two
parameters.
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>

Gandhinagar Institute of Technology 3161611 AWP


<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>

 The return Statement:


A JavaScript function can have an optional return statement. This is required if you want to
return a value from a function. This statement should be the last statement in a function.
For example, you can pass two numbers in a function and then you can expect the function to
return their multiplication in your calling program.

Example:
Try the following example. It defines a function that takes two parameters and concatenates
them before returning the resultant in the calling program.
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>

Gandhinagar Institute of Technology 3161611 AWP


Exercise:
1. Write JavaScript Program to Solve Quadratic Equation.
2. Write JavaScript Program to Check Armstrong Number.
3. Write JavaScript Program to Convert Decimal to Binary

Review Questions:
1. Can an anonymous function be assigned to a variable?
2. If we want to return the character from a specific index which method is used?
3. What is the difference between JavaScript and JScript?

Gandhinagar Institute of Technology 3161611 AWP


Event, Cookies, Page redirect
Practical No: __________ Date: __________

Aim: Study of JavaScript’s event, cookies, page redirect.

Theory
What is an Event?
JavaScript's interaction with HTML is handled through events that occur when the user or
the browser manipulates a page.

When the page loads, it is called an event. When the user clicks a button, that click too is an
event. Other examples include events like pressing any key, closing a window, resizing a
window, etc.

Developers can use these events to execute JavaScript coded responses, which cause
buttons to close windows, messages to be displayed to users, data to be validated, and
virtually any other type of response imaginable.

Events are a part of the Document Object Model (DOM) Level 3 and every HTML element
contains a set of events which can trigger JavaScript Code.

Please go through this small tutorial for a better understanding HTML Event Reference.
Here we will see a few examples to understand a relation between Event and JavaScript −

 onclick Event Type:


This is the most frequently used event type which occurs when a user clicks the left button
of his mouse. You can put your validation, warning etc., against this event type.

Example:
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>

Gandhinagar Institute of Technology 3161611 AWP


<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>

 onsubmit Event Type:

onsubmit is an event that occurs when you try to submit a form. You can put your form
validation against this event type.
Here we are calling a validate() function before submitting a form data to the webserver.
If validate() function returns true, the form will be submitted, otherwise it will not submit the
data.
Example:
<html>
<head>
<script type = "text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body></html>

Gandhinagar Institute of Technology 3161611 AWP


 onmouseover and onmouseout:

These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and
the onmouseout triggers when you move your mouse out from that element. Try the following
Example:
<html>
<head>
<script type = "text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>

What are Cookies?

Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless
protocol. But for a commercial website, it is required to maintain session information among
different pages. For example, one user registration ends after completing many pages. But
how to maintain users' session information across all the web pages.
In many situations, using cookies is the most efficient method of remembering and tracking
preferences, purchases, commissions, and other information required for better visitor
experience or site statistics.
Gandhinagar Institute of Technology 3161611 AWP
How It Works?

Your server sends some data to the visitor's browser in the form of a cookie. The browser may
accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now,
when the visitor arrives at another page on your site, the browser sends the same cookie to the
server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.
Cookies are a plain text data record of 5 variable-length fields −
 Expires − the date the cookie will expire. If this is blank, the cookie will expire when
the visitor quits the browser.
 Domain − the domain name of your site.
 Path − the path to the directory or web page that set the cookie. This may be blank if
you want to retrieve the cookie from any directory or page.
 Secure − If this field contains the word "secure", then the cookie may only be retrieved
with a secure server. If this field is blank, no such restriction exists.
 Name=Value − Cookies are set and retrieved in the form of key-value pairs
Cookies were originally designed for CGI programming. The data contained in a cookie is
automatically transmitted between the web browser and the web server, so CGI scripts on the
server can read and write cookie values that are stored on the client.
JavaScript can also manipulate cookies using the cookie property of the Document object.
JavaScript can read, create, modify, and delete the cookies that apply to the current web page.

 Storing Cookies

The simplest way to create a cookie is to assign a string value to the document.cookie object,
which looks like this.
document.cookie = "key1 = value1;key2 = value2;expires = date";
Here the expires attribute is optional. If you provide this attribute with a valid date or time,
then the cookie will expire on a given date or time and thereafter, the cookies' value will not
be accessible.
Note − Cookie values may not include semicolons, commas, or whitespace. For this reason,
you may want to use the JavaScript escape() function to encode the value before storing it in
the cookie. If you do this, you will also have to use the corresponding unescape() function
when you read the cookie value.

Example:
<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {

Gandhinagar Institute of Technology 3161611 AWP


if( document.myform.customer.value == "" ) {
alert("Enter some value!");
return;
}
cookievalue = escape(document.myform.customer.value) + ";";
document.cookie = "name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
</form>
</body>
</html>

 Reading Cookies:

Reading a cookie is just as simple as writing one, because the value of the document.cookie
object is the cookie. So you can use this string whenever you want to access the cookie. The
document.cookie string will keep a list of name=value pairs separated by semicolons,
where name is the name of a cookie and value is its string value.
You can use strings' split() function to break a string into key and values as follows −

Example:
<html>
<head>
<script type = "text/javascript">
<!--
function ReadCookie() {
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );

Gandhinagar Institute of Technology 3161611 AWP


// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');

// Now take key value pair out of this array


for(var i=0; i<cookiearray.length; i++) {
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name = "myform" action = "">
<p> click the following button and see the result:</p>
<input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
</form>
</body>
</html>
Note − Here length is a method of Array class which returns the length of an array. We will
discuss Arrays in a separate chapter. By that time, please try to digest it.
Note − There may be some other cookies already set on your machine. The above code will
display all the cookies set on your machine.

 Setting Cookies Expiry Date

You can extend the life of a cookie beyond the current browser session by setting an expiration
date and saving the expiry date within the cookie. This can be done by setting
the ‘expires’ attribute to a date and time.

Example:
<html>
<head>

Gandhinagar Institute of Technology 3161611 AWP


<script type = "text/javascript">
<!--
function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"

document.cookie = "name=" + cookievalue;


document.cookie = "expires=" + now.toUTCString() + ";"
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>

 Deleting a Cookie

Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie
return nothing. To do this, you just need to set the expiry date to a time in the past.

JavaScript - Page Redirection

What is Page Redirection?

You might have encountered a situation where you clicked a URL to reach a page X but
internally you were directed to another page Y. It happens due to page redirection. This
concept is different from JavaScript Page Refresh.
There could be various reasons why you would like to redirect a user from the original page.
We are listing down a few of the reasons −

Gandhinagar Institute of Technology 3161611 AWP


 You did not like the name of your domain and you are moving to a new one. In such a
scenario, you may want to direct all your visitors to the new site. Here you can maintain
your old domain but put a single page with a page redirection such that all your old
domain visitors can come to your new domain.
 You have built-up various pages based on browser versions or their names or may be
based on different countries, then instead of using your server-side page redirection,
you can use client-side page redirection to land your users on the appropriate page.
 The Search Engines may have already indexed your pages. But while moving to
another domain, you would not like to lose your visitors coming through search
engines. So you can use client-side page redirection. But keep in mind this should not
be done to fool the search engine, it could lead your site to get banned.

How Page Re-direction Works?

The implementations of Page-Redirection are as follows.

Example:
It is quite simple to do a page redirect using JavaScript at client side. To redirect your site
visitors to a new page, you just need to add a line in your head section as follows.
<html>
<head>
<script type = "text/javascript">
<!--
function Redirect() {
window.location = "https://www.tutorialspoint.com";
}
//-->
</script>
</head>
<body>
<p>Click the following button, you will be redirected to home page.</p>

<form>
<input type = "button" value = "Redirect Me" onclick = "Redirect();" />
</form>

</body>
</html>

Example:
You can show an appropriate message to your site visitors before redirecting them to a new
page. This would need a bit time delay to load a new page. The following example shows how
to implement the same. Here setTimeout() is a built-in JavaScript function which can be used
to execute another function after a given time interval.

Gandhinagar Institute of Technology 3161611 AWP


<html>
<head>
<script type = "text/javascript">
<!--
function Redirect() {
window.location = "https://www.tutorialspoint.com";
}
document.write("You will be redirected to main page in 10 sec.");
setTimeout('Redirect()', 10000);
//-->
</script>
</head>
<body>
</body>
</html>
Exercise:
1. Write a JavaScript to redirect your site visitors onto a different page based on their browsers.
2. Write a javascript to delete a cookie by setting its expiry date to one month behind the
current date.
3. Write a javascript “When the input field gets focus, a function is triggered which changes
the background-color:
Review Questions:
1. What’s Event Delegation?
2. In which location cookies are stored on the hard disk?
3. What are ‘event.target’ and ‘event.currentTarget’

Gandhinagar Institute of Technology 3161611 AWP


[This page is intentionally left blank]

Gandhinagar Institute of Technology 3161611 AWP


JavaScript Object
Practical No: __________ Date: __________

Aim: Study of JavaScript Object.


Theory

JavaScript is an Object Oriented Programming (OOP) language. A programming language


can be called object-oriented if it provides four basic capabilities to developers −
 Encapsulation − the capability to store related information, whether data or methods,
together in an object.
 Aggregation − the capability to store one object inside another object.
 Inheritance − the capability of a class to rely upon another class (or number of classes)
for some of its properties and methods.
 Polymorphism − the capability to write one function or method that works in a variety
of different ways.
Objects are composed of attributes. If an attribute contains a function, it is considered to be a
method of the object, otherwise the attribute is considered a property.
 Object Properties:
Object properties can be any of the three primitive data types, or any of the abstract data types,
such as another object. Object properties are usually variables that are used internally in the
object's methods, but can also be globally visible variables that are used throughout the page.
The syntax for adding a property to an object is −
objectName.objectProperty = propertyValue;
Example:
The following code gets the document title using the "title" property of the document object.
var str = document.title;
 Object Methods:
Methods are the functions that let the object do something or let something be done to it. There
is a small difference between a function and a method – at a function is a standalone unit of
statements and a method is attached to an object and can be referenced by the this keyword.
Methods are useful for everything from displaying the contents of the object to the screen to
performing complex mathematical operations on a group of local properties and parameters.
Example: Following is a simple example to show how to use the write() method of document
object to write any content on the document.
document.write("This is test");
 User-Defined Objects:
All user-defined objects and built-in objects are descendants of an object called Object.
 The new Operator:
The new operator is used to create an instance of an object. To create an object,
the new operator is followed by the constructor method.
In the following example, the constructor methods are Object(), Array(), and Date(). These
constructors are built-in JavaScript functions.

Gandhinagar Institute of Technology 3161611 AWP


Example:
var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");

 The Object() Constructor


A constructor is a function that creates and initializes an object. JavaScript provides a special
constructor function called Object() to build the object. The return value of
the Object() constructor is assigned to a variable.
The variable contains a reference to the new object. The properties assigned to the object are
not variables and are not defined with the var keyword.
Example:
Try the following example; it demonstrates how to create an Object.
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
book.author = "Mohtashim";
</script>
</head>

<body>
<script type = "text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
Output:
Book name is : Perl
Book author is : Mohtashim

Example:
This example demonstrates how to create an object with a User-Defined Function.
Here this keyword is used to refer to the object that has been passed to a function.

Gandhinagar Institute of Technology 3161611 AWP


<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
function book(title, author) {
this.title = title;
this.author = author;
}
</script>
</head>

<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>

Output:
Book title is : Perl
Book author is : Mohtashim
Defining Methods for an Object
The previous examples demonstrate how the constructor creates the object and assigns
properties. But we need to complete the definition of an object by assigning methods to it.
Example:
Try the following example; it shows how to add a function along with an object.
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
// Define a function which will work as a method
function addPrice(amount) {
this.price = amount;
}
function book(title, author) {
this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type = "text/javascript">
Gandhinagar Institute of Technology 3161611 AWP
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script> </body></html>
Output:
Book title is: Perl
Book author is: Mohtashim
Book price is: 100
The 'with' Keyword
The ‘with’ keyword is used as a kind of shorthand for referencing an object's properties or
methods.
The object specified as an argument to with becomes the default object for the duration of the
block that follows. The properties and methods for the object can be used without naming the
object.
Syntax: The syntax for with object is as follows;
with (object)
{ properties used without the object name and dot
}
 JavaScript Native Objects
JavaScript has several built-in or native objects. These objects are accessible anywhere in
your program and will work the same way in any browser running in any operating system.

Here is the list of all important JavaScript Native Objects −

o JavaScript Number Object


o JavaScript Boolean Object
o JavaScript String Object
o JavaScript Array Object
o JavaScript Date Object
o JavaScript Math Object
o JavaScript RegExp Object
Exercise:
1. Write a JavaScript splits a String object into an array of strings by separating the
string into substrings.
2. Write a JavaScript causes a string to blink as if it were in a BLINK tag.
3. Write a JavaScript use of NAN number object.
Review Questions:
1. What is a potential pitfall with using typeof bar === "object" to determine if bar is an
object? How can this pitfall be avoided?
2. How do you clone an object?

Gandhinagar Institute of Technology 3161611 AWP


Bootstrap
Practical No: __________ Date: __________

Aim: Study of Bootstrap


Theory
Bootstrap was developed by Mark Otto and Jacob Thornton at Twitter. It was released as an
open source product in August 2011 on GitHub.
Why Use Bootstrap?
 Mobile first approach − Bootstrap 3, framework consists of Mobile first styles
throughout the entire library instead them of in separate files.
 Browser Support − It is supported by all popular browsers.
 Easy to get started − With just the knowledge of HTML and CSS anyone can get
started with Bootstrap. Also the Bootstrap official site has a good documentation.
 Responsive design − Bootstrap's responsive CSS adjusts to Desktops, Tablets and
Mobiles. More about the responsive design is in the chapter Bootstrap Responsive
Design.
 Provides a clean and uniform solution for building an interface for developers.
 It contains beautiful and functional built-in components which are easy to customize.
 It also provides web based customization.
 And best of all it is an open source.

What Bootstrap Package Includes?

 Scaffolding − Bootstrap provides a basic structure with Grid System, link styles, and
background. This is is covered in detail in the section Bootstrap Basic Structure
 CSS − Bootstrap comes with the feature of global CSS settings, fundamental HTML
elements styled and enhanced with extensible classes, and an advanced grid system.
This is covered in detail in the section Bootstrap with CSS.
 Components − Bootstrap contains over a dozen reusable components built to provide
iconography, dropdowns, navigation, alerts, pop-overs, and much more. This is
covered in detail in the section Layout Components.
 JavaScript Plugins − Bootstrap contains over a dozen custom jQuery plugins. You
can easily include them all, or one by one. This is covered in details in the
section Bootstrap Plugins.
 Customize − You can customize Bootstrap's components, LESS variables, and jQuery
plugins to get your very own version.
 It is very easy to setup and start using Bootstrap. This chapter will explain how to
download and setup Bootstrap. We will also discuss the Bootstrap file structure, and
demonstrate its usage with an example.
 Download Bootstrap
 You can download the latest version of Bootstrap from https://getbootstrap.com/.
When you click on this link, you will get to see a screen as below −
Here you can see two buttons −
 Download Bootstrap − Clicking this, you can download the precompiled and minified
versions of Bootstrap CSS, JavaScript, and fonts. No documentation or original source
code files are included.
 Download Source − Clicking this, you can get the latest Bootstrap LESS and
JavaScript source code directly from GitHub.

Gandhinagar Institute of Technology 3161611 AWP


For better understanding and ease of use, we shall use precompiled version of
Bootstrap throughout the tutorial. As the files are complied and minified you don't
have to bother every time including separate files for individual functionality. At the
time of writing this tutorial the latest version (Bootstrap 3) was downloaded

 File structure

Precompiled Bootstrap
Once the compiled version Bootstrap is downloaded, extract the ZIP file, and you will see the
following file/directory structure −

Fig 1: Precompiled Bootstrap


As you can see, there are compiled CSS and JS (bootstrap.*), as well as compiled and minified
CSS and JS (bootstrap.min.*). Fonts from Glyphicons are included, as it is the optional
Bootstrap theme.

Bootstrap Source Code


If you have downloaded the Bootstrap source code then the file structure would be as follows

Fig 2: Bootstrap Source Code


 The files under less/, js/, and fonts/ are the source code for Bootstrap CSS, JS, and icon
fonts (respectively).
 The dist/ folder includes everything listed in the precompiled download section above.

Gandhinagar Institute of Technology 3161611 AWP


 docs-assets/, examples/, and all *.html files are Bootstrap documentation.

 HTML Template

A basic HTML template using Bootstrap would look like this


Syntax:
<!DOCTYPE html>
<html>

<head>
<title>Bootstrap 101 Template</title>
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0">

<!-- Bootstrap -->


<link href = "css/bootstrap.min.css" rel = "stylesheet">

<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --
>
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->

<!--[if lt IE 9]>
<script src = "https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src = "https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->

</head>

<body>
<h1>Hello, world!</h1>

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->


<script src = "https://code.jquery.com/jquery.js"></script>

<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src = "js/bootstrap.min.js"></script>

</body>
</html>
Here you can see the jquery.js, bootstrap.min.js and bootstrap.min.css files that are
included to make a normal HTM file to the Bootstrapped Template. Just make sure to include
jQuery library before you include Bootstrap library.

What is Bootstrap Grid System?

As put by the official documentation of Bootstrap for grid system −


Gandhinagar Institute of Technology 3161611 AWP
Bootstrap includes a responsive, mobile first fluid grid system that appropriately scales up to
12 columns as the device or viewport size increases. It includes predefined classes for easy
layout options, as well as powerful mixins for generating more semantic layouts.
Let us understand the above statement. Bootstrap 3 is mobile first in the sense that the code
for Bootstrap now starts by targeting smaller screens like mobile devices, tablets, and then
“expands” components and grids for larger screens such as laptops, desktops.

 Mobile First Strategy


 Content
o Determine what is most important.
 Layout
o Design to smaller widths first.
o Base CSS address mobile device first; media queries address for tablet,
desktops.
 Progressive Enhancement
o Add elements as screen size increases.

Working of Bootstrap Grid System

Grid systems are used for creating page layouts through a series of rows and columns that
house your content. Here's how the Bootstrap grid system works −
 Rows must be placed within a .container class for proper alignment and padding.
 Use rows to create horizontal groups of columns.
 Content should be placed within the columns, and only columns may be the immediate
children of rows.
 Predefined grid classes like .row and .col-xs-4 are available for quickly making grid
layouts. LESS mixins can also be used for more semantic layouts.
 Columns create gutters (gaps between column content) via padding. That padding is
offset in rows for the first and the last column via negative margin on .rows.
 Grid columns are created by specifying the number of twelve available columns you
wish to span. For example, three equal columns would use three .col-xs-4.

 Bootstrap - Tables
Bootstrap provides a clean layout for building tables. Some of the table elements supported
by Bootstrap are −

Sr.No. Tag & Description

1
<table>
Wrapping element for displaying data in a tabular format

Gandhinagar Institute of Technology 3161611 AWP


2
<thead>
Container element for table header rows (<tr>) to label table columns.

3
<tbody>
Container element for table rows (<tr>) in the body of the table.

4
<tr>
Container element for a set of table cells (<td> or <th>) that appears on a single row.

5
<td>
Default table cell.

6
<th>
Special table cell for column (or row, depending on scope and placement) labels. Must be
used within a <thead>

7
<caption>
Description or summary of what the table holds.

 Optional Table Classes

Along with the base table markup and the .table class, there are a few additional classes that
you can use to style the markup. Following sections will give you a glimpse of all these
classes.

Striped Table
By adding the .table-striped class, you will get stripes on rows within the <tbody> as seen in
the following example −
Example:
<table class = "table table-striped">
<caption>Striped Table Layout</caption>
<thead>
<tr>
<th>Name</th>
<th>City</th>
<th>Pincode</th>
</tr>
</thead>

Gandhinagar Institute of Technology 3161611 AWP


<tbody>
<tr>
<td>Tanmay</td>
<td>Bangalore</td>
<td>560001</td>
</tr>
<tr>
<td>Sachin</td>
<td>Mumbai</td>
<td>400003</td>
</tr>

<tr>
<td>Uma</td>
<td>Pune</td>
<td>411027</td>
</tr>
</tbody>
</table>
Output:

 Bootstrap - Forms

Form Layout

Bootstrap provides you with following types of form layouts −


 Vertical (default) form
 In-line form
 Horizontal form
Vertical or Basic Form
The basic form structure comes with Bootstrap; individual form controls automatically receive
some global styling. To create a basic form do the following −
 Add a role form to the parent <form> element.
 Wrap labels and controls in a <div> with class .form-group. This is needed for optimum
spacing.
 Add a class of .form-control to all textual <input>, <textarea>, and <select> elements.
Example:
<form role = "form">
<div class = "form-group">
<label for = "name">Name</label>
<input type = "text" class = "form-control" id = "name" placeholder = "Enter Name">
Gandhinagar Institute of Technology 3161611 AWP
</div>

<div class = "form-group">


<label for = "inputfile">File input</label>
<input type = "file" id = "inputfile">
<p class = "help-block">Example block-level help text here.</p>
</div>

<div class = "checkbox">


<label><input type = "checkbox"> Check me out</label>
</div>

<button type = "submit" class = "btn btn-default">Submit</button>


</form>
Output:

Inline Form
To create a form where all of the elements are inline, left aligned and labels are alongside, add
the class .form-inline to the <form> tag.
Example:
<form class = "form-inline" role = "form">
<div class = "form-group">
<label class = "sr-only" for = "name">Name</label>
<input type = "text" class = "form-control" id = "name" placeholder = "Enter Name">
</div>
<div class = "form-group">
<label class = "sr-only" for = "inputfile">File input</label>
<input type = "file" id = "inputfile">
</div>
<div class = "checkbox">
<label><input type = "checkbox"> Check me out</label>
</div>
<button type = "submit" class = "btn btn-default">Submit</button>
</form>

Gandhinagar Institute of Technology 3161611 AWP


Horizontal Form
Horizontal forms stands apart from the others not only in the amount of markup, but also in
the presentation of the form. To create a form that uses the horizontal layout, do the following
 Add a class of .form-horizontal to the parent <form> element.
 Wrap labels and controls in a <div> with class .form-group.
 Add a class of .control-label to the labels.
Example:
<form class = "form-horizontal" role = "form">
<div class = "form-group">
<label for = "firstname" class = "col-sm-2 control-label">First Name</label>

<div class = "col-sm-10">


<input type = "text" class = "form-control" id = "firstname" placeholder = "Enter First
Name">
</div>
</div>
<div class = "form-group">
<label for = "lastname" class = "col-sm-2 control-label">Last Name</label>
<div class = "col-sm-10">
<input type = "text" class = "form-control" id = "lastname" placeholder = "Enter Last
Name">
</div>
</div>
<div class = "form-group">
<div class = "col-sm-offset-2 col-sm-10">
<div class = "checkbox">
<label><input type = "checkbox"> Remember me</label>
</div>
</div>
</div>
<div class = "form-group">
<div class = "col-sm-offset-2 col-sm-10">
<button type = "submit" class = "btn btn-default">Sign in</button>
</div>
</div>
</form>
Output:

Gandhinagar Institute of Technology 3161611 AWP


 Textarea
The textarea is used when you need multiple lines of input. Change rows attribute as necessary
(fewer rows = smaller box, more rows = bigger box).
Example:
<form role = "form">
<div class = "form-group">
<label for = "name">Text Area</label>
<textarea class = "form-control" rows = "3"></textarea>
</div>
</form>
CheckBoxes and Radio Buttons
Checkboxes and radio buttons are great when you want users to choose from a list of preset
options.
 When building a form, use checkbox if you want the user to select any number of
options from a list. Use radio if you want to limit the user to just one selection.
 Use .checkbox-inline or .radio-inline class to a series of checkboxes or radios for
controls appear on the same line.
The following example demonstrates both (default and inline) types −
Example:
<label for = "name">Example of Default Checkbox and radio button </label>
<div class = "checkbox">
<label>
<input type = "checkbox" value = "">Option 1
</label>
</div>
<div class = "checkbox">
<label>
<input type = "checkbox" value = "">Option 2
</label>
</div>
<div class = "radio">
<label>
<input type = "radio" name = "optionsRadios" id = "optionsRadios1" value = "option1"
checked> Option 1
</label>
</div>
<div class = "radio">
<label>
<input type = "radio" name = "optionsRadios" id = "optionsRadios2" value = "option2">
Option 2 - selecting it will deselect option 1
</label>
</div>
<label for = "name">Example of Inline Checkbox and radio button </label>
<div>
<label class = "checkbox-inline">
<input type = "checkbox" id = "inlineCheckbox1" value = "option1"> Option 1
</label>
<label class = "checkbox-inline">
<input type = "checkbox" id = "inlineCheckbox2" value = "option2"> Option 2
</label>
Gandhinagar Institute of Technology 3161611 AWP
<label class = "checkbox-inline">
<input type = "checkbox" id = "inlineCheckbox3" value = "option3"> Option 3
</label>
<label class = "checkbox-inline">
<input type = "radio" name = "optionsRadiosinline" id = "optionsRadios3" value =
"option1" checked> Option 1
</label>
<label class = "checkbox-inline">
<input type = "radio" name = "optionsRadiosinline" id = "optionsRadios4" value =
"option2"> Option 2
</label>
</div>
Output:

Exercise:
Create a registration form using bootstrap. According below figure.

Review Questions:
1. Enlist key components of Bootstrap?
2. Give an example of a basic grid structure in Bootstrap.
3. What is column ordering in Bootstrap?

Gandhinagar Institute of Technology 3161611 AWP


Introduction of AngularJS
Practical No: __________ Date: __________

Aim: To understand Basics of AngularJS.


Theory
AngularJS is a very powerful JavaScript Framework. It is used in Single Page Application
(SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive
to user actions. AngularJS is open source, completely free, and used by thousands of developers
around the world. It is licensed under the Apache license version 2.0.

Why to Learn AngularJS?


AngularJS is an open-source web application framework. It was originally developed in 2009
by Misko Hevery and Adam Abrons. It is now maintained by Google. Its latest version is
1.2.21.
 AngularJS is a efficient framework that can create Rich Internet Applications (RIA).
 AngularJS provides developers an options to write client side applications using
JavaScript in a clean Model View Controller (MVC) way.
 Applications written in AngularJS are cross-browser compliant. AngularJS
automatically handles JavaScript code suitable for each browser.
 AngularJS is open source, completely free, and used by thousands of developers around
the world. It is licensed under the Apache license version 2.0.
Overall, AngularJS is a framework to build large scale, high-performance, and easyto-
maintain web applications.
 Applications of AngularJS
The general features of AngularJS are as follows −
 AngularJS is a efficient framework that can create Rich Internet Applications (RIA).
 AngularJS provides developers an options to write client side applications using
JavaScript in a clean Model View Controller (MVC) way.
 Applications written in AngularJS are cross-browser compliant. AngularJS
automatically handles JavaScript code suitable for each browser.
 AngularJS is open source, completely free, and used by thousands of developers around
the world. It is licensed under the Apache license version 2.0.
Overall, AngularJS is a framework to build large scale, high-performance, and easyto-
maintain web applications.

AngularJS is an open-source web application framework. It was originally developed in 2009


by Misko Hevery and Adam Abrons. It is now maintained by Google. Its latest version is
1.2.21.
 General Features
The general features of AngularJS are as follows −
 AngularJS is a efficient framework that can create Rich Internet Applications (RIA).
 AngularJS provides developers an options to write client side applications using
JavaScript in a clean Model View Controller (MVC) way.
 Applications written in AngularJS are cross-browser compliant. AngularJS
automatically handles JavaScript code suitable for each browser.
 AngularJS is open source, completely free, and used by thousands of developers around
the world. It is licensed under the Apache license version 2.0.
Overall, AngularJS is a framework to build large scale, high-performance, and easyto-
maintain web applications.
Core Features
Gandhinagar Institute of Technology 3161611 AWP
The core features of AngularJS are as follows −
 Data-binding − It is the automatic synchronization of data between model and view
components.
 Scope − These are objects that refer to the model. They act as a glue between controller
and view.
 Controller − These are JavaScript functions bound to a particular scope.
 Services − AngularJS comes with several built-in services such as $http to make a
XMLHttpRequests. These are singleton objects which are instantiated only once in
app.
 Filters − These select a subset of items from an array and returns a new array.
 Directives − Directives are markers on DOM elements such as elements, attributes,
css, and more. These can be used to create custom HTML tags that serve as new,
custom widgets. AngularJS has built-in directives such as ngBind, ngModel, etc.
 Templates − These are the rendered view with information from the controller and
model. These can be a single file (such as index.html) or multiple views in one page
using partials.
 Routing − It is concept of switching views.
 Model View Whatever − MVW is a design pattern for dividing an application into
different parts called Model, View, and Controller, each with distinct responsibilities.
AngularJS does not implement MVC in the traditional sense, but rather something
closer to MVVM (Model-View-ViewModel). The Angular JS team refers it
humorously as Model View Whatever.
 Deep Linking − Deep linking allows to encode the state of application in the URL so
that it can be bookmarked. The application can then be restored from the URL to the
same state.
 Dependency Injection − AngularJS has a built-in dependency injection subsystem that
helps the developer to create, understand, and test the applications easily.
 Concepts
The following diagram depicts some important parts of AngularJS which we will discuss in
detail in the subsequent topics.

Gandhinagar Institute of Technology 3161611 AWP


 Advantages of AngularJS
The advantages of AngularJS are −
 It provides the capability to create Single Page Application in a very clean and
maintainable way.
 It provides data binding capability to HTML. Thus, it gives user a rich and responsive
experience.
 AngularJS code is unit testable.
 AngularJS uses dependency injection and make use of separation of concerns.
 AngularJS provides reusable components.
 With AngularJS, the developers can achieve more functionality with short code.
 In AngularJS, views are pure html pages, and controllers written in JavaScript do the
business processing.
On the top of everything, AngularJS applications can run on all major browsers and smart
phones, including Android and iOS based phones/tablets.
 Disadvantages of AngularJS
Though AngularJS comes with a lot of merits, here are some points of concern −
 Not Secure − Being JavaScript only framework, application written in AngularJS are
not safe. Server side authentication and authorization is must to keep an application
secure.
 Not degradable − If the user of your application disables JavaScript, then nothing
would be visible, except the basic page.

 AngularJS Directives
The AngularJS framework can be divided into three major parts −
 ng-app − This directive defines and links an AngularJS application to HTML.
 ng-model − This directive binds the values of AngularJS application data to HTML
input controls.
 ng-bind − This directive binds the AngularJS application data to HTML tags.

 AngularJS - Environment Setup


When you open the link https://angularjs.org/, you will see there are two options to download
AngularJS library −

Gandhinagar Institute of Technology 3161611 AWP


 View on GitHub − By clicking on this button, you are diverted to GitHub and get all
the latest scripts.
 Download AngularJS 1 − By clicking on this button, a screen you get to see a dialog
box shown as −

This screen gives various options of using Angular JS as follows −


 Downloading and hosting files locally
o There are two different options : Legacy and Latest. The names themselves are
self-descriptive. The Legacy has version less than 1.2.x and the Latest come
with version 1.3.x.
o We can also go with the minimized, uncompressed, or zipped version.
 CDN access − You also have access to a CDN. The CDN gives you access to regional
data centers. In this case, the Google host. The CDN transfers the responsibility of
hosting files from your own servers to a series of external ones. It also offers an
advantage that if the visitor of your web page has already downloaded a copy of
AngularJS from the same CDN, there is no need to re-download it.

 AngularJS - MVC Architecture


Model View Controller or MVC as it is popularly called, is a software design pattern for
developing web applications. A Model View Controller pattern is made up of the following
three parts −
 Model − It is the lowest level of the pattern responsible for maintaining data.
 View − It is responsible for displaying all or a portion of the data to the user.
 Controller − It is a software Code that controls the interactions between the Model and
View.
MVC is popular because it isolates the application logic from the user interface layer and
supports separation of concerns. The controller receives all requests for the application and
then works with the model to prepare any data needed by the view. The view then uses the
data prepared by the controller to generate a final presentable response. The MVC abstraction
can be graphically represented as follows.
Gandhinagar Institute of Technology 3161611 AWP
Fig. 1: MVC abstraction

 The Model
The model is responsible for managing application data. It responds to the request from view
and to the instructions from controller to update itself.
The View
A presentation of data in a particular format, triggered by the controller's decision to present
the data. They are script-based template systems such as JSP, ASP, PHP and very easy to
integrate with AJAX technology.
The Controller
The controller responds to user input and performs interactions on the data model objects. The
controller receives input, validates it, and then performs business operations that modify the
state of the data model.
AngularJS is a MVC based framework. In the coming chapters, we will see how AngularJS
uses MVC methodology.
 AngularJS - First Application
Before creating actual Hello World ! application using AngularJS, let us see the parts of a
AngularJS application. An AngularJS application consists of following three important parts
 ng-app − This directive defines and links an AngularJS application to HTML.
 ng-model − This directive binds the values of AngularJS application data to HTML
input controls.
 ng-bind − This directive binds the AngularJS Application data to HTML tags.

Gandhinagar Institute of Technology 3161611 AWP


 Creating AngularJS Application
Step 1: Load framework
Being a pure JavaScript framework, it can be added using <Script> tag.
<script
src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
Step 2: Define AngularJS application using ng-app directive
<div ng-app = "">
...
</div>
Step 3: Define a model name using ng-model directive
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
Step 4: Bind the value of above model defined using ng-bind directive
<p>Hello <span ng-bind = "name"></span>!</p>
Executing AngularJS Application
Use the above-mentioned three steps in an HTML page.
testAngularJS.htm
Example:
<html>
<head>
<title>AngularJS First Application</title>
</head>
<body>
<h1>Sample Application</h1>
<div ng-app = "">
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
<p>Hello <span ng-bind = "name"></span>!</p>
</div>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</body></html>
Output:

How AngularJS Integrates with HTML


 The ng-app directive indicates the start of AngularJS application.
 The ng-model directive creates a model variable named name, which can be used with
the HTML page and within the div having ng-app directive.
 The ng-bind then uses the name model to be displayed in the HTML <span> tag
whenever user enters input in the text box.
 Closing</div> tag indicates the end of AngularJS application.

Gandhinagar Institute of Technology 3161611 AWP


 AngularJS - Directives
AngularJS directives are used to extend HTML. They are special attributes starting with ng-
prefix. Let us discuss the following directives −
 ng-app − This directive starts an AngularJS Application.
 ng-init − This directive initializes application data.
 ng-model − This directive defines the model that is variable to be used in AngularJS.
 ng-repeat − This directive repeats HTML elements for each item in a collection.
ng-app directive
The ng-app directive starts an AngularJS Application. It defines the root element. It
automatically initializes or bootstraps the application when the web page containing
AngularJS Application is loaded. It is also used to load various AngularJS modules in
AngularJS Application. In the following example, we define a default AngularJS application
using ng-app attribute of a <div> element.
<div ng-app = "">
...
</div>
ng-init directive
The ng-init directive initializes an AngularJS Application data. It is used to assign values to
the variables. In the following example, we initialize an array of countries. We use JSON
syntax to define the array of countries.
<div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'},
{locale:'en-GB',name:'United Kingdom'}, {locale:'en-FR',name:'France'}]">
...
</div>
ng-model directive
The ng-model directive defines the model/variable to be used in AngularJS Application. In
the following example, we define a model named name.
<div ng-app = "">
...
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
</div>
ng-repeat directive
The ng-repeat directive repeats HTML elements for each item in a collection. In the following
example, we iterate over the array of countries.
Example:
<div ng-app = "">
...
<p>List of Countries with locale:</p>

<ol>
<li ng-repeat = "country in countries">
{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
</li>
</ol>
</div>
Example:
The following example shows the use of all the above-mentioned directives.
testAngularJS.htm

<html>
<head>
<title>AngularJS Directives</title>
Gandhinagar Institute of Technology 3161611 AWP
</head>
<body>
<h1>Sample Application</h1>
<div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'},
{locale:'en-GB',name:'United Kingdom'}, {locale:'en-FR',name:'France'}]">
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
<p>Hello <span ng-bind = "name"></span>!</p>
<p>List of Countries with locale:</p>
<ol>
<li ng-repeat = "country in countries">
{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
</li>
</ol>
</div>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</body>
</html>

 AngularJS - Controllers
AngularJS application mainly relies on controllers to control the flow of data in the
application. A controller is defined using ng-controller directive. A controller is a JavaScript
object that contains attributes/properties, and functions. Each controller accepts $scope as a
parameter, which refers to the application/module that the controller needs to handle.
<div ng-app = "" ng-controller = "studentController">
...
</div>
Here, we declare a controller named studentController, using the ng-controller directive. We
define it as follows
Example:
<script>
function studentController($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",

Gandhinagar Institute of Technology 3161611 AWP


fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
} }; }
</script>
 The studentController is defined as a JavaScript object with $scope as an argument.
 The $scope refers to application which uses the studentController object.
 The $scope.student is a property of studentController object.
 The firstName and the lastName are two properties of $scope.student object. We pass
the default values to them.
 The property fullName is the function of $scope.student object, which returns the
combined name.
 In the fullName function, we get the student object and then return the combined name.
 As a note, we can also define the controller object in a separate JS file and refer that
file in the HTML page.
Now we can use studentController's student property using ng-model or using expressions as
follows −
Enter first name: <input type = "text" ng-model = "student.firstName"><br>
Enter last name: <input type = "text" ng-model = "student.lastName"><br>
<br>
You are entering: {{student.fullName()}}
 We bound student.firstName and student.lastname to two input boxes.
 We bound student.fullName() to HTML.
 Now whenever you type anything in first name and last name input boxes, you can see
the full name getting updated automatically.
Example
The following example shows the use of controller −
testAngularJS.htm
<html>
<head>
<title>Angular JS Controller</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "studentController">
Enter first name: <input type = "text" ng-model = "student.firstName"><br>
<br>
Enter last name: <input type = "text" ng-model = "student.lastName"><br>
<br>
You are entering: {{student.fullName()}}
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fullName: function() {
var studentObject;
Gandhinagar Institute of Technology 3161611 AWP
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
</script>
</body>
</html>

 AngularJS - Modules
AngularJS supports modular approach. Modules are used to separate logic such as services,
controllers, application etc. from the code and maintain the code clean. We define modules in
separate js files and name them as per the module.js file. In the following example, we are
going to create two modules −
 Application Module − used to initialize an application with controller(s).
 Controller Module − used to define the controller.
Application Module
Here is a file named mainApp.js that contains the following code −
var mainApp = angular.module("mainApp", []);
Here, we declare an application mainApp module using angular.module function and pass an
empty array to it. This array generally contains dependent modules.
Controller Module

studentController.js
Example:
mainApp.controller("studentController", function($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fees:500,
subjects:[
{name:'Physics',marks:70},
{name:'Chemistry',marks:80},
{name:'Math',marks:65},
{name:'English',marks:75},
{name:'Hindi',marks:67}
],
fullName: function() {
var studentObject;
Gandhinagar Institute of Technology 3161611 AWP
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
Here, we declare a controller studentController module using mainApp.controller function.
Use Modules
<div ng-app = "mainApp" ng-controller = "studentController">
...
<script src = "mainApp.js"></script>
<script src = "studentController.js"></script>

</div>
Here, we use application module using ng-app directive, and controller using ngcontroller
directive. We import the mainApp.js and studentController.js in the main HTML page.
Example
The following example shows use of all the above mentioned modules.
testAngularJS.htm
Example:
<html>
<head>
<title>Angular JS Modules</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src = "/angularjs/src/module/mainApp.js"></script>
<script src = "/angularjs/src/module/studentController.js"></script>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "studentController">
<table border = "0">
<tr>
<td>Enter first name:</td>
<td><input type = "text" ng-model = "student.firstName"></td>
</tr>
<tr>
<td>Enter last name: </td>
<td><input type = "text" ng-model = "student.lastName"></td>
Gandhinagar Institute of Technology 3161611 AWP
</tr>
<tr>
<td>Name: </td>
<td>{{student.fullName()}}</td>
</tr>
<tr>
<td>Subject:</td>
<td>
<table>
<tr>
<th>Name</th>
<th>Marks</th>
</tr>
<tr ng-repeat = "subject in student.subjects">
<td>{{ subject.name }}</td>
<td>{{ subject.marks }}</td>
</tr>
</table>
</td>
</tr>
</table>
</div> </body> </html>
mainApp.js
var mainApp = angular.module("mainApp", []);
studentController.js
mainApp.controller("studentController", function($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fees:500,
subjects:[
{name:'Physics',marks:70},
{name:'Chemistry',marks:80},
{name:'Math',marks:65},
{name:'English',marks:75},
{name:'Hindi',marks:67}
],
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});

Gandhinagar Institute of Technology 3161611 AWP


Exercise:
1. Write a program to print “Welcome to GIT” using controllers module.

Review Questions:
1. Can there be two ng-app for a single angular application?
2. Name a few inbuilt angular filters?
3. What are custom filters? Write down a syntax of the same?

Gandhinagar Institute of Technology 3161611 AWP


[This page is intentionally left blank]

Gandhinagar Institute of Technology 3161611 AWP


AngularJS’s forms, AJAX and Views
Practical No: __________ Date: __________

Aim: To study AngularJS’s forms, AJAX, Views.

Theory
AngularJS enriches form filling and validation. We can use ng-click event to handle the click
button and use $dirty and $invalid flags to do the validation in a seamless way. Use novalidate
with a form declaration to disable any browser-specific validation. The form controls make
heavy use of AngularJS events. Let us have a look at the events first.
Events
AngularJS provides multiple events associated with the HTML controls. For example, ng-
click directive is generally associated with a button. AngularJS supports the following events

 ng-click
 ng-dbl-click
 ng-mousedown
 ng-mouseup
 ng-mouseenter
 ng-mouseleave
 ng-mousemove
 ng-mouseover
 ng-keydown
 ng-keyup
 ng-keypress
 ng-change
ng-click
Reset data of a form using on-click directive of a button.
Example:
<input name = "firstname" type = "text" ng-model = "firstName" required>
<input name = "lastname" type = "text" ng-model = "lastName" required>
<input name = "email" type = "email" ng-model = "email" required>
<button ng-click = "reset()">Reset</button>
<script>
function studentController($scope) {
$scope.reset = function() {
$scope.firstName = "Mahesh";
$scope.lastName = "Parashar";
$scope.email = "[email protected]";
}
$scope.reset();
}
</script>
 Validate Data
The following can be used to track error.
 $dirty − states that value has been changed.
 $invalid − states that value entered is invalid.
 $error − states the exact error.
Example
The following example will showcase all the above-mentioned directives.
testAngularJS.htm
Gandhinagar Institute of Technology 3161611 AWP
<html>
<head>
<title>Angular JS Forms</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px; }
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style> </head> <body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "studentController">

<form name = "studentForm" novalidate>


<table border = "0">
<tr>
<td>Enter first name:</td>
<td><input name = "firstname" type = "text" ng-model = "firstName" required>
<span style = "color:red" ng-show = "studentForm.firstname.$dirty &&
studentForm.firstname.$invalid">
<span ng-show = "studentForm.firstname.$error.required">First Name is
required.</span>
</span> </td> </tr> <tr>
<td>Enter last name: </td>
<td><input name = "lastname" type = "text" ng-model = "lastName" required>
<span style = "color:red" ng-show = "studentForm.lastname.$dirty &&
studentForm.lastname.$invalid">
<span ng-show = "studentForm.lastname.$error.required">Last Name is
required.</span>
</span>
</td>
</tr> <tr>
<td>Email: </td><td><input name = "email" type = "email" ng-model = "email"
length = "100" required>
<span style = "color:red" ng-show = "studentForm.email.$dirty &&
studentForm.email.$invalid">
<span ng-show = "studentForm.email.$error.required">Email is
required.</span>
<span ng-show = "studentForm.email.$error.email">Invalid email
address.</span>
</span>
</td>
</tr>

<tr>
Gandhinagar Institute of Technology 3161611 AWP
<td>
<button ng-click = "reset()">Reset</button>
</td>
<td>
<button ng-disabled = "studentForm.firstname.$dirty &&
studentForm.firstname.$invalid || studentForm.lastname.$dirty &&
studentForm.lastname.$invalid || studentForm.email.$dirty &&
studentForm.email.$invalid" ng-click="submit()">Submit</button>
</td>
</tr>
</table>
</form>
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope) {
$scope.reset = function() {
$scope.firstName = "Mahesh";
$scope.lastName = "Parashar";
$scope.email = "[email protected]";
}
$scope.reset();
});
</script> </body></html>

 AngularJS - Includes
HTML does not support embedding HTML pages within the HTML page. To achieve this
functionality, we can use one of the following options −
 Using Ajax − Make a server call to get the corresponding HTML page and set it in the
innerHTML of HTML control.
 Using Server Side Includes − JSP, PHP and other web side server technologies can
include HTML pages within a dynamic page.
Using AngularJS, we can embed HTML pages within an HTML page using ng-include
directive.
<div ng-app = "" ng-controller = "studentController">
<div ng-include = "'main.htm'"></div>
<div ng-include = "'subjects.htm'"></div>
</div>

Gandhinagar Institute of Technology 3161611 AWP


 AngularJS - Ajax
AngularJS provides $http control which works as a service to read data from the server. The
server makes a database call to get the desired records. AngularJS needs data in JSON format.
Once the data is ready, $http can be used to get the data from server in the following manner
Example:
function studentController($scope,$https:) {
var url = "data.txt";
$https:.get(url).success( function(response) {
$scope.students = response;
});
}
Here, the file data.txt contains student records. $http service makes an ajax call and sets
response to its property students. students model can be used to draw tables in HTML.
Example:
data.txt
[
{
"Name" : "Mahesh Parashar",
"RollNo" : 101,
"Percentage" : "80%"
},
{
"Name" : "Dinkar Kad",
"RollNo" : 201,
"Percentage" : "70%"
},
{
"Name" : "Robert",
"RollNo" : 191,
"Percentage" : "75%"
},
{
"Name" : "Julian Joe",
"RollNo" : 111,
"Percentage" : "77%"
}
]
testAngularJS.htm
Example:
<html>
<head>
<title>Angular JS Includes</title>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
Gandhinagar Institute of Technology 3161611 AWP
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head><body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "" ng-controller = "studentController">
<table>
<tr>
<th>Name</th>
<th>Roll No</th>
<th>Percentage</th>
</tr>
<tr ng-repeat = "student in students">
<td>{{ student.Name }}</td>
<td>{{ student.RollNo }}</td>
<td>{{ student.Percentage }}</td>
</tr>
</table>
</div>
<script>
function studentController($scope,$http) {
var url = "/data.txt";

$http.get(url).then( function(response) {
$scope.students = response.data;
});
}
</script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
</script> </body></html>

 AngularJS - Views
AngularJS supports Single Page Application via multiple views on a single page. To do this,
AngularJS has provided ng-view and ng-template directives, and $routeProvider services.
ng-view Directive
The ng-view directive simply creates a place holder where a corresponding view (HTML or
ng-template view) can be placed based on the configuration.
Gandhinagar Institute of Technology 3161611 AWP
Usage
Define a div with ng-view within the main module.
<div ng-app = "mainApp">
...
<div ng-view></div>

</div>
ng-template Directive
The ng-template directive is used to create an HTML view using script tag. It
contains id attribute which is used by $routeProvider to map a view with a controller.
Usage
Define a script block with type as ng-template within the main module.
<div ng-app = "mainApp">
...
<script type = "text/ng-template" id = "addStudent.htm">
<h2> Add Student </h2>
{{message}}
</script>
</div>
$routeProvider Service
The $routeProvider is a key service which sets the configuration of URLs, maps them with
the corresponding HTML page or ng-template, and attaches a controller with the same.
Usage 1
Define a script block with type as ng-template within the main module.
<div ng-app = "mainApp">
..
<script type = "text/ng-template" id = "addStudent.htm">
<h2> Add Student </h2>
{{message}}
</script>
</div>
Usage 2
Define a script block with main module and set the routing configuration.
var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/addStudent', {
templateUrl: 'addStudent.htm', controller: 'AddStudentController'
})
.when('/viewStudents', {
templateUrl: 'viewStudents.htm', controller: 'ViewStudentsController'
})
.otherwise ({
redirectTo: '/addStudent'
});
}]);
The following points are important to be considered in the above example
 $routeProvider is defined as a function under config of mainApp module using key as
'$routeProvider'.
 $routeProvider.when defines a URL "/addStudent", which is mapped to
"addStudent.htm". addStudent.htm should be present in the same path as main HTML

Gandhinagar Institute of Technology 3161611 AWP


page. If the HTML page is not defined, then ng-template needs to be used with
id="addStudent.htm". We used ng-template.
 "otherwise" is used to set the default view.
 "controller" is used to set the corresponding controller for the view.
Example:
The following example shows the use of all the above-mentioned directives.
testAngularJS.htm
<html>
<head>
<title>Angular JS Views</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-
route.min.js">
</script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp">
<p><a href = "#addStudent">Add Student</a></p>
<p><a href = "#viewStudents">View Students</a></p>
<div ng-view></div>
<script type = "text/ng-template" id = "addStudent.htm">
<h2> Add Student </h2>
{{message}}
</script>
<script type = "text/ng-template" id = "viewStudents.htm">
<h2> View Students </h2>
{{message}}
</script>
</div>
<script>
var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/addStudent', {
templateUrl: 'addStudent.htm',
controller: 'AddStudentController'
})
.when('/viewStudents', {
templateUrl: 'viewStudents.htm',
controller: 'ViewStudentsController'
})
.otherwise({
redirectTo: '/addStudent'
});
}]);
mainApp.controller('AddStudentController', function($scope) {
$scope.message = "This page will be used to display add student form";
});
mainApp.controller('ViewStudentsController', function($scope) {
$scope.message = "This page will be used to display all the students";
Gandhinagar Institute of Technology 3161611 AWP
});
</script> </body></html>

Exercise:
1. Write a program for validation using AngularJs Forms.
2. Implement program using AJAX. We have the file data.txt, which will include the
records of the student. An ajax call will be made by the $http service. It is going to
divert & set the response to the students having priority. After this extraction, the tables
will be drawn up in the HTML, which will be based on the students model.
The data.txt file:
[ {
"Name" : "Ronaldo",
"Goals" : 128,
"Ratio" : "69%"
},
{
"Name" : "James",
"Goals" : 007,
"Ratio" : "70%"
},
{
"Name" : "Ali",
"Goals" : 786,
"Ratio" : "99%"
},
{
"Name" : "Lionel ",
"Goals" : 210,
"Ratio" : "100%"
}]

Review Questions:
1. Where should one use form action instead of $http for accessing a method on a
server?
2. Explain the styling form that ngModel adds to CSS classes

Gandhinagar Institute of Technology 3161611 AWP


AngularJS Services, Dependency Injection
Practical No: __________ Date: __________

Aim:

Theory
AngularJS supports the concept of Separation of Concerns using services architecture.
Services are JavaScript functions, which are responsible to perform only specific tasks. This
makes them individual entities which are maintainable and testable. The controllers and filters
can call them on requirement basis. Services are normally injected using the dependency
injection mechanism of AngularJS.
AngularJS provides many inbuilt services. For example, $http, $route, $window, $location,
etc. Each service is responsible for a specific task such as the $http is used to make ajax call
to get the server data, the $route is used to define the routing information, and so on. The
inbuilt services are always prefixed with $ symbol.
There are two ways to create a service −
 Factory
 Service
 Using Factory Method
In this method, we first define a factory and then assign method to it.
var mainApp = angular.module("mainApp", []);
mainApp.factory('MathService', function() {
var factory = {};

factory.multiply = function(a, b) {
return a * b
}

return factory;
});
 Using Service Method
In this method, we define a service and then assign method to it. We also inject an already
available service to it.
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
Example:
The following example shows use of all the above mentioned directives −
testAngularJS.htm
<html>
<head>
<title>Angular JS Services</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</head>

<body>
<h2>AngularJS Sample Application</h2>

Gandhinagar Institute of Technology 3161611 AWP


<div ng-app = "mainApp" ng-controller = "CalcController">
<p>Enter a number: <input type = "number" ng-model = "number" /></p>
<button ng-click = "square()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div>

<script>
var mainApp = angular.module("mainApp", []);

mainApp.factory('MathService', function() {
var factory = {};

factory.multiply = function(a, b) {
return a * b
}
return factory;
});
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
mainApp.controller('CalcController', function($scope, CalcService) {
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
</script>

</body>
</html>

AngularJS - Dependency Injection


Dependency Injection is a software design in which components are given their dependencies
instead of hard coding them within the component. It relieves a component from locating the
dependency and makes dependencies configurable. It also helps in making components
reusable, maintainable and testable.
AngularJS provides a supreme Dependency Injection mechanism. It provides following core
components which can be injected into each other as dependencies.
 Value
 Factory
Gandhinagar Institute of Technology 3161611 AWP
 Service
 Provider
 Constant
 Value
Value is a simple JavaScript object, which is required to pass values to the controller during
config phase (config phase is when AngularJS bootstraps itself).
//define a module
var mainApp = angular.module("mainApp", []);

//create a value object as "defaultInput" and pass it a data.


mainApp.value("defaultInput", 5);
...
//inject the value in the controller using its name "defaultInput"
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);

$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
 Factory
Factory is a function which is used to return value. It creates a value on demand whenever a
service or a controller requires it. It generally uses a factory function to calculate and return
the value.
//define a module
var mainApp = angular.module("mainApp", []);

//create a factory "MathService" which provides a method multiply to return multiplication of


two numbers
mainApp.factory('MathService', function() {
var factory = {};

factory.multiply = function(a, b) {
return a * b
}
return factory;
});
//inject the factory "MathService" in a service to utilize the multiply method of factory.
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
 Service
Service is a singleton JavaScript object containing a set of functions to perform certain tasks.
Service is defined using service() function and it is then injected into the controllers.
//define a module
var mainApp = angular.module("mainApp", []);
...
//create a service which defines a method square to return square of a number.
mainApp.service('CalcService', function(MathService) {
Gandhinagar Institute of Technology 3161611 AWP
this.square = function(a) {
return MathService.multiply(a,a);
}
});
//inject the service "CalcService" into the controller
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);

$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
 Provider
Provider is used by AngularJS internally to create services, factory, etc. during the config
phase. The following script can be used to create MathService that we created earlier. Provider
is a special factory method with get() method which is used to return the value/service/factory.
//define a module
var mainApp = angular.module("mainApp", []);
...
//create a service using provider which defines a method square to return square of a number.
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};

factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});
 Constant
Constants are used to pass values at the config phase considering the fact that value cannot be
used during the config phase.
mainApp.constant("configParam", "constant value");
Example:
The following example shows the use of all the above-mentioned directives −
testAngularJS.htm
<html>
<head>
<title>AngularJS Dependency Injection</title>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "CalcController">
<p>Enter a number: <input type = "number" ng-model = "number" /></p>
<button ng-click = "square()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div>

Gandhinagar Institute of Technology 3161611 AWP


<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>

<script>
var mainApp = angular.module("mainApp", []);

mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};

factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});
mainApp.value("defaultInput", 5);
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
});
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);

$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
</script>
</body>
</html>

Gandhinagar Institute of Technology 3161611 AWP


Exercise:

1. Create a service using AngularJS Factory Service.


2. Create a service using AngularJS Http Post Method

Review Questions:

1. How to make an ajax call using Angular JS?


2. What are the differences between service and factory methods?
3. Which components can be injected as a dependency in AngularJS?

Gandhinagar Institute of Technology 3161611 AWP


Introduction of NodeJs
Practical No: __________ Date: __________

Aim: To understand Basics of AngularJS.

Theory
Node.js is a very powerful JavaScript-based platform built on Google Chrome's JavaScript V8
Engine. It is used to develop I/O intensive web applications like video streaming sites, single-
page applications, and other web applications. Node.js is open source, completely free, and
used by thousands of developers around the world.
 What is Node.js?
Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8 Engine).
Node.js was developed by Ryan Dahl in 2009 and its latest version is v0.10.36. The definition
of Node.js as supplied by its official documentation is as follows −
o Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and
scalable network applications. Node.js uses an event-driven, non-blocking I/O model
that makes it lightweight and efficient, perfect for data-intensive real-time applications
that run across distributed devices.
o Node.js is an open source, cross-platform runtime environment for developing server-
side and networking applications. Node.js applications are written in JavaScript, and
can be run within the Node.js runtime on OS X, Microsoft Windows, and Linux.
o Node.js also provides a rich library of various JavaScript modules which simplifies the
development of web applications using Node.js to a great extent.
o Node.js = Runtime Environment + JavaScript Library
 Features of Node.js
Following are some of the important features that make Node.js the first choice of software
architects.
o Asynchronous and Event Driven − All APIs of Node.js library are asynchronous,
that is, non-blocking. It essentially means a Node.js based server never waits for an
API to return data. The server moves to the next API after calling it and a notification
mechanism of Events of Node.js helps the server to get a response from the previous
API call.
o Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is
very fast in code execution.
o Single Threaded but Highly Scalable − Node.js uses a single threaded model with
event looping. Event mechanism helps the server to respond in a non-blocking way and
makes the server highly scalable as opposed to traditional servers which create limited
threads to handle requests. Node.js uses a single threaded program and the same
program can provide service to a much larger number of requests than traditional
servers like Apache HTTP Server.
o No Buffering − Node.js applications never buffer any data. These applications simply
output the data in chunks.
o License − Node.js is released under the MIT license.
 Who Uses Node.js?
Following is the link on github wiki containing an exhaustive list of projects, application and
companies which are using Node.js. This list includes eBay, General Electric, GoDaddy,
Microsoft, PayPal, Uber, Wikipins, Yahoo!, and Yammer to name a few.

 Projects, Applications, and Companies Using Node

Gandhinagar Institute of Technology 3161611 AWP


 Concepts
The following diagram depicts some important parts of Node.js which we will discuss in detail
in the subsequent chapters.

Fig 1: Parts of Node.js.

 Where to Use Node.js?


Following are the areas where Node.js is proving itself as a perfect technology partner.
 I/O bound Applications
 Data Streaming Applications
 Data Intensive Real-time Applications (DIRT)
 JSON APIs based Applications
 Single Page Applications
Where Not to Use Node.js?
It is not advisable to use Node.js for CPU intensive applications.
Try it Option Online
You really do not need to set up your own environment to start learning Node.js. Reason is
very simple, we already have set up Node.js environment online, so that you can execute all
the available examples online and learn through practice. Feel free to modify any example and
check the results with different options.
Try the following example using the Live Demo option available at the top right corner of the
below sample code box (on our website) −
/* Hello World! program in Node.js */
console.log("Hello World!");

For most of the examples given in this tutorial, you will find a Try it option, so just make use
of it and enjoy your learning.
 Local Environment Setup
If you are still willing to set up your environment for Node.js, you need the following two
softwares available on your computer, (a) Text Editor and (b) The Node.js binary installables.
Gandhinagar Institute of Technology 3161611 AWP
Text Editor
This will be used to type your program. Examples of few editors include Windows Notepad,
OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
Name and version of text editor can vary on different operating systems. For example,
Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or
UNIX.
The files you create with your editor are called source files and contain program source code.
The source files for Node.js programs are typically named with the extension ".js".
Before starting your programming, make sure you have one text editor in place and you have
enough experience to write a computer program, save it in a file, and finally execute it.
The Node.js Runtime
The source code written in source file is simply javascript. The Node.js interpreter will be
used to interpret and execute your javascript code.
Node.js distribution comes as a binary installable for SunOS , Linux, Mac OS X, and Windows
operating systems with the 32-bit (386) and 64-bit (amd64) x86 processor architectures.
Following section guides you on how to install Node.js binary distribution on various OS.
Download Node.js archive
Download latest version of Node.js installable archive file from Node.js Downloads. At the
time of writing this tutorial, following are the versions available on different OS.
Table 1: Node.js versions available on different OS
OS Archive name

Windows node-v6.3.1-x64.msi

Linux node-v6.3.1-linux-x86.tar.gz

Mac node-v6.3.1-darwin-x86.tar.gz

SunOS node-v6.3.1-sunos-x86.tar.gz

Installation on UNIX/Linux/Mac OS X, and SunOS


Based on your OS architecture, download and extract the archive node-v6.3.1-osname.tar.gz
into /tmp, and then finally move extracted files into /usr/local/nodejs directory. For example:
$ cd /tmp
$ wget http://nodejs.org/dist/v6.3.1/node-v6.3.1-linux-x64.tar.gz
$ tar xvfz node-v6.3.1-linux-x64.tar.gz
$ mkdir -p /usr/local/nodejs
$ mv node-v6.3.1-linux-x64/* /usr/local/nodejs
Add /usr/local/nodejs/bin to the PATH environment variable.
Table 1: Download path on different OS
OS Output

Linux export PATH=$PATH:/usr/local/nodejs/bin

Mac export PATH=$PATH:/usr/local/nodejs/bin

FreeBSD export PATH=$PATH:/usr/local/nodejs/bin

Gandhinagar Institute of Technology 3161611 AWP


 Installation on Windows
Use the MSI file and follow the prompts to install the Node.js. By default, the installer uses
the Node.js distribution in C:\Program Files\nodejs. The installer should set the C:\Program
Files\nodejs\bin directory in window's PATH environment variable. Restart any open
command prompts for the change to take effect.
Verify installation: Executing a File
Create a js file named main.js on your machine (Windows or Linux) having the following
code.
/* Hello, World! program in node.js */
console.log("Hello, World!")
Now execute main.js file using Node.js interpreter to see the result −
$ node main.js
If everything is fine with your installation, this should produce the following result −
Hello, World!
 First Application
Before creating an actual "Hello, World!" application using Node.js, let us see the components
of a Node.js application. A Node.js application consists of the following three important
components −
o Import required modules − We use the require directive to load Node.js modules.
o Create server − A server which will listen to client's requests similar to Apache HTTP
Server.
o Read request and return response − The server created in an earlier step will read
the HTTP request made by the client which can be a browser or a console and return
the response.
Creating Node.js Application
Step 1 - Import Required Module
We use the require directive to load the http module and store the returned HTTP instance
into an http variable as follows −
var http = require("http");
Step 2 - Create Server
We use the created http instance and call http.createServer() method to create a server
instance and then we bind it at port 8081 using the listen method associated with the server
instance. Pass it a function with parameters request and response. Write the sample
implementation to always return "Hello World".
Example:
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
The above code is enough to create an HTTP server which listens, i.e., waits for a request over
8081 port on the local machine.
Step 3 - Testing Request & Response
Let's put step 1 and 2 together in a file called main.js and start our HTTP server as shown
below −
var http = require("http");

Gandhinagar Institute of Technology 3161611 AWP


http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

Now execute the main.js to start the server as follows −


$ node main.js

Verify the Output. Server has started.


Server running at http://127.0.0.1:8081/
Make a Request to the Node.js Server
Open http://127.0.0.1:8081/ in any browser and observe the following result.

Congratulations, you have your first HTTP server up and running which is responding to all
the HTTP requests at port 8081.
 REPL Terminal
REPL stands for Read Eval Print Loop and it represents a computer environment like a
Windows console or Unix/Linux shell where a command is entered and the system responds
with an output in an interactive mode. Node.js or Node comes bundled with a REPL
environment. It performs the following tasks −
o Read − Reads user's input, parses the input into JavaScript data-structure, and stores
in memory.
o Eval − Takes and evaluates the data structure.
o Print − Prints the result.
o Loop − Loops the above command until the user presses ctrl-c twice.
The REPL feature of Node is very useful in experimenting with Node.js codes and to debug
JavaScript codes.

Gandhinagar Institute of Technology 3161611 AWP


Online REPL Terminal
To simplify your learning, we have set up an easy to use Node.js REPL environment online,
where you can practice Node.js syntax − Launch Node.js REPL Terminal
Starting REPL
REPL can be started by simply running node on shell/console without any arguments as
follows.
$ node
You will see the REPL Command prompt > where you can type any Node.js command −
$ node
>
Simple Expression
Let's try a simple mathematics at the Node.js REPL command prompt −
$ node
>1+3
4
>1+(2*3)-4
3
>
Use Variables
You can make use variables to store values and print later like any conventional script.
If var keyword is not used, then the value is stored in the variable and printed. Whereas
if var keyword is used, then the value is stored but not printed. You can print variables
using console.log().
$ node
> x = 10
10
> var y = 10
undefined
>x+y
20
> console.log("Hello World")
Hello World
undefined
Multiline Expression
Node REPL supports multiline expression similar to JavaScript. Let's check the following do-
while loop in action −
$ node
> var x = 0
undefined
> do {
... x++;
... console.log("x: " + x);
... }
while ( x < 5 );
x: 1
x: 2
x: 3
x: 4
x: 5
undefined
>

Gandhinagar Institute of Technology 3161611 AWP


... comes automatically when you press Enter after the opening bracket. Node automatically
checks the continuity of expressions.
Underscore Variable
You can use underscore (_) to get the last result −
$ node
> var x = 10
undefined
> var y = 20
undefined
>x+y
30
> var sum = _
undefined
> console.log(sum)
30
undefined
>
 REPL Commands
 ctrl + c − terminate the current command.
 ctrl + c twice − terminate the Node REPL.
 ctrl + d − terminate the Node REPL.
 Up/Down Keys − see command history and modify previous commands.
 tab Keys − list of current commands.
 .help − list of all commands.
 .break − exit from multiline expression.
 .clear − exit from multiline expression.
 .save filename − save the current Node REPL session to a file.
 .load filename − load file content in current Node REPL session.
Stopping REPL
As mentioned above, you will need to use ctrl-c twice to come out of Node.js REPL.
$ node
>
(^C again to quit)
>
 NPM
Node Package Manager (NPM) provides two main functionalities −
 Online repositories for node.js packages/modules which are searchable
on search.nodejs.org
 Command line utility to install Node.js packages, do version management and
dependency management of Node.js packages.
NPM comes bundled with Node.js installables after v0.6.3 version. To verify the same, open
console and type the following command and see the result −
$ npm --version
2.7.1
If you are running an old version of NPM then it is quite easy to update it to the latest version.
Just use the following command from root −
$ sudo npm install npm -g
/usr/bin/npm -> /usr/lib/node_modules/npm/bin/npm-cli.js
[email protected] /usr/lib/node_modules/npm
Installing Modules using NPM
There is a simple syntax to install any Node.js module −
$ npm install <Module Name>
Gandhinagar Institute of Technology 3161611 AWP
For example, following is the command to install a famous Node.js web framework module
called express −
$ npm install express
Now you can use this module in your js file as following −
var express = require('express');
Global vs Local Installation
By default, NPM installs any dependency in the local mode. Here local mode refers to the
package installation in node_modules directory lying in the folder where Node application is
present. Locally deployed packages are accessible via require() method. For example, when
we installed express module, it created node_modules directory in the current directory where
it installed the express module.
$ ls -l
total 0
drwxr-xr-x 3 root root 20 Mar 17 02:23 node_modules
Alternatively, you can use npm ls command to list down all the locally installed modules.
Globally installed packages/dependencies are stored in system directory. Such dependencies
can be used in CLI (Command Line Interface) function of any node.js but cannot be imported
using require() in Node application directly. Now let's try installing the express module using
global installation.
$ npm install express -g
This will produce a similar result but the module will be installed globally. Here, the first line
shows the module version and the location where it is getting installed.
[email protected] /usr/lib/node_modules/express
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected] ([email protected])
├── [email protected] ([email protected])
├── [email protected] ([email protected])
├── [email protected] ([email protected], [email protected])
├── [email protected] ([email protected], [email protected], [email protected])
├── [email protected] ([email protected])
├── [email protected] ([email protected], [email protected])
└── [email protected] ([email protected], [email protected])
You can use the following command to check all the modules installed globally −
$ npm ls -g
Uninstalling a Module
Use the following command to uninstall a Node.js module.
$ npm uninstall express
Gandhinagar Institute of Technology 3161611 AWP
Once NPM uninstalls the package, you can verify it by looking at the content of
/node_modules/ directory or type the following command −
$ npm ls
Updating a Module
Update package.json and change the version of the dependency to be updated and run the
following command.
$ npm update express
Search a Module
Search a package name using NPM.
$ npm search express
Create a Module
Creating a module requires package.json to be generated. Let's generate package.json using
NPM, which will generate the basic skeleton of the package.json.
$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sane defaults.

See 'npm help json' for definitive documentation on these fields


and exactly what they do.

Use 'npm install <pkg> --save' afterwards to install a package and


save it as a dependency in the package.json file.

Press ^C at any time to quit.


name: (webmaster)
You will need to provide all the required information about your module. You can take help
from the above-mentioned package.json file to understand the meanings of various
information demanded. Once package.json is generated, use the following command to
register yourself with NPM repository site using a valid email address.
$ npm adduser
Username: mcmohd
Password:
Email: (this IS public) [email protected]
It is time now to publish your module −
$ npm publish
If everything is fine with your module, then it will be published in the repository and will be
accessible to install using NPM like any other Node.js module.

 Callbacks
What is Callback?
Callback is an asynchronous equivalent for a function. A callback function is called at the
completion of a given task. Node makes heavy use of callbacks. All the APIs of Node are
written in such a way that they support callbacks.
For example, a function to read a file may start reading file and return the control to the
execution environment immediately so that the next instruction can be executed. Once file I/O
is complete, it will call the callback function while passing the callback function, the content
of the file as a parameter. So there is no blocking or wait for File I/O. This makes Node.js
highly scalable, as it can process a high number of requests without waiting for any function
to return results.
 Blocking Code Example
Create a text file named input.txt with the following content −
Tutorials Point is giving self learning content
Gandhinagar Institute of Technology 3161611 AWP
to teach the world in simple and easy way!!!!!
Create a js file named main.js with the following code −
var fs = require("fs");
var data = fs.readFileSync('input.txt');

console.log(data.toString());
console.log("Program Ended");
Now run the main.js to see the result −
$ node main.js
Verify the Output.
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Program Ended
 Non-Blocking Code Example
Create a text file named input.txt with the following content.
GIT is best college in Gujarat,
to teach the world in simple and easy way!!!!!
Update main.js to have the following code −
var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program Ended");
Now run the main.js to see the result −
$ node main.js
Verify the Output.
Program Ended
GIT is best college in Gujarat,to teach the world in simple and easy way!!!!!
These two examples explain the concept of blocking and non-blocking calls.
 The first example shows that the program blocks until it reads the file and then only it
proceeds to end the program.
 The second example shows that the program does not wait for file reading and proceeds
to print "Program Ended" and at the same time, the program without blocking
continues reading the file.
Thus, a blocking program executes very much in sequence. From the programming point of
view, it is easier to implement the logic but non-blocking programs do not execute in
sequence. In case a program needs to use any data to be processed, it should be kept within
the same block to make it sequential execution.

Exercise:
1. Create a Calculator Node.js Module with functions add, subtract and multiply. And
use the Calculator module in another Node.js file.
2. Create a file with data provided and read, write and delete data
Review Questions:
1. Why is Node.js preferred over other backend technologies like Java and PHP?
2. What is an EventEmitter in Node.js?
3. How would you use a URL module in Node.js?

Gandhinagar Institute of Technology 3161611 AWP


Connection between MongoDB and NodeJs
Practical No: __________ Date: __________

Aim: Implement database connection between mongodb and nodejs.

Theory

MongoDB is an open-source document database and leading NoSQL database. MongoDB is


written in C++. This tutorial will give you great understanding on MongoDB concepts needed
to create and deploy a highly scalable and performance-oriented database.

 Database
Database is a physical container for collections. Each database gets its own set of files on the
file system. A single MongoDB server typically has multiple databases.
Collection
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A
collection exists within a single database. Collections do not enforce a schema. Documents
within a collection can have different fields. Typically, all documents in a collection are of
similar or related purpose.
 Document
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema
means that documents in the same collection do not need to have the same set of fields or
structure, and common fields in a collection's documents may hold different types of data.
Table 1: Relationship of RDBMS terminology with MongoDB.
RDBMS MongoDB

Database Database

Table Collection

Tuple/Row Document

column Field

Table Join Embedded Documents

Primary Key Primary Key (Default key _id provided by


MongoDB itself)

Database Server and Client

mysqld/Oracle mongod

mysql/sqlplus mongo

Any relational database has a typical schema design that shows number of tables and the
relationship between these tables. While in MongoDB, there is no concept of relationship.
 Advantages of MongoDB over RDBMS
o Schema less − MongoDB is a document database in which one collection holds
different documents. Number of fields, content and size of the document can differ
from one document to another.
Gandhinagar Institute of Technology 3161611 AWP
o Structure of a single object is clear.
o No complex joins.
o Deep query-ability. MongoDB supports dynamic queries on documents using a
document-based query language that's nearly as powerful as SQL.
o Tuning.
o Ease of scale-out − MongoDB is easy to scale.
o Conversion/mapping of application objects to database objects not needed.
o Uses internal memory for storing the (windowed) working set, enabling faster access
of data.
Why Use MongoDB?
o Document Oriented Storage − Data is stored in the form of JSON style documents.
o Index on any attribute
o Replication and high availability
o Auto-Sharding
o Rich queries
o Fast in-place updates
o Professional support by MongoDB
Where to Use MongoDB?
o Big Data
o Content Management and Delivery
o Mobile and Social Infrastructure
o User Data Management
o Data Hub
 Install MongoDB On Windows
To install MongoDB on Windows, first download the latest release of MongoDB
from https://www.mongodb.com/download-center.

Gandhinagar Institute of Technology 3161611 AWP


Enter the required details, select the Server tab, in it you can choose the version of MongoDB,
operating system and, packaging as:

Now install the downloaded file, by default, it will be installed in the folder C:\Program
Files\.

MongoDB requires a data folder to store its files. The default location for the MongoDB data
directory is c:\data\db. So you need to create this folder using the Command Prompt. Execute
the following command sequence.
C:\>md data
C:\md data\db
Then you need to specify set the dbpath to the created directory in mongod.exe. For the same,
issue the following commands.
In the command prompt, navigate to the bin directory current in the MongoDB installation
folder.
Suppose my installation folder is C:\Program Files\MongoDB
C:\Users\XYZ>d:cd C:\Program Files\MongoDB\Server\4.2\bin
C:\Program Files\MongoDB\Server\4.2\bin>mongod.exe --dbpath "C:\data"
This will show waiting for connections message on the console output, which indicates that
the mongod.exe process is running successfully.
Now to run the MongoDB, you need to open another command prompt and issue the following
command.
C:\Program Files\MongoDB\Server\4.2\bin>mongo.exe
MongoDB shell version v4.2.1
connecting to:
mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("4260beda-f662-4cbe-9bc7-5c1f2242663c") }
MongoDB server version: 4.2.1
>
This will show that MongoDB is installed and run successfully. Next time when you run
MongoDB, you need to issue only commands.

Gandhinagar Institute of Technology 3161611 AWP


C:\Program Files\MongoDB\Server\4.2\bin>mongod.exe --dbpath "C:\data"
C:\Program Files\MongoDB\Server\4.2\bin>mongo.exe
 Install MongoDB on Ubuntu
Run the following command to import the MongoDB public GPG key −
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
Create a /etc/apt/sources.list.d/mongodb.list file using the following command.
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen'
| sudo tee /etc/apt/sources.list.d/mongodb.list
Now issue the following command to update the repository −
sudo apt-get update
Next install the MongoDB by using the following command −
apt-get install mongodb-10gen = 4.2
In the above installation, 2.2.3 is currently released MongoDB version. Make sure to install
the latest version always. Now MongoDB is installed successfully.
 Start MongoDB
sudo service mongodb start
Stop MongoDB
sudo service mongodb stop
Restart MongoDB
sudo service mongodb restart
To use MongoDB run the following command.
mongo
This will connect you to running MongoDB instance.
 MongoDB Help
To get a list of commands, type db.help() in MongoDB client. This will give you a list of
commands as shown in the following screenshot.

Gandhinagar Institute of Technology 3161611 AWP


 MongoDB Statistics
To get stats about MongoDB server, type the command db.stats() in MongoDB client. This
will show the database name, number of collection and documents in the database. Output of
the command is shown in the following screenshot.

 Create Database
The use Command
MongoDB use DATABASE_NAME is used to create database. The command will create a
new database if it doesn't exist, otherwise it will return the existing database.
Syntax
Basic syntax of use DATABASE statement is as follows −
use DATABASE_NAME
Example:
If you want to use a database with name <mydb>, then use DATABASE statement would be
as follows −
>use mydb
switched to db mydb

To check your currently selected database, use the command db


>db
mydb
If you want to check your databases list, use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB
Your created database (mydb) is not present in list. To display database, you need to insert at
least one document into it.
>db.movie.insert({"name":"tutorials point"})
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
In MongoDB default database is test. If you didn't create any database, then collections will
be stored in test database.
The dropDatabase() Method
MongoDB db.dropDatabase() command is used to drop a existing database.
Syntax:
Basic syntax of dropDatabase() command is as follows −
Gandhinagar Institute of Technology 3161611 AWP
db.dropDatabase()
This will delete the selected database. If you have not selected any database, then it will delete
default 'test' database.
Example:
First, check the list of available databases by using the command, show dbs.
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
>
If you want to delete new database <mydb>, then dropDatabase() command would be as
follows −
>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>
Now check list of databases.
>show dbs
local 0.78125GB
test 0.23012GB
>
MongoDB supports many datatypes. Some of them are −
o String − This is the most commonly used datatype to store the data. String in
MongoDB must be UTF-8 valid.
o Integer − This type is used to store a numerical value. Integer can be 32 bit or 64 bit
depending upon your server.
o Boolean − This type is used to store a boolean (true/ false) value.
o Double − This type is used to store floating point values.
o Min/ Max keys − This type is used to compare a value against the lowest and highest
BSON elements.
o Arrays − This type is used to store arrays or list or multiple values into one key.
o Timestamp − ctimestamp. This can be handy for recording when a document has been
modified or added.
o Object − This datatype is used for embedded documents.
o Null − This type is used to store a Null value.
o Symbol − This datatype is used identically to a string; however, it's generally reserved
for languages that use a specific symbol type.
o Date − This datatype is used to store the current date or time in UNIX time format.
You can specify your own date time by creating object of Date and passing day, month,
year into it.
o Object ID − This datatype is used to store the document’s ID.
o Binary data − This datatype is used to store binary data.
o Code − This datatype is used to store JavaScript code into the document.
 Regular expression − This datatype is used to store regular expression. The
createCollection() Method
MongoDB db.createCollection(name, options) is used to create collection.
Syntax:
Basic syntax of createCollection() command is as follows
db.createCollection(name, options)
In the command, name is name of collection to be created. Options is a document and is used
to specify configuration of collection.
Gandhinagar Institute of Technology 3161611 AWP
Tabel 2: Regular expression syntax
Parameter Type Description

Name String Name of the collection to be created

Options Document (Optional) Specify options about memory size and


indexing
Options parameter is optional, so you need to specify only the name of the collection.
Tabel 3: list of options
Field Type Description

(Optional) If true, enables a capped collection. Capped collection is a


fixed size collection that automatically overwrites its oldest entries when
capped Boolean
it reaches its maximum size. If you specify true, you need to specify size
parameter also.

(Optional) If true, automatically create index on _id field.s Default value


autoIndexId Boolean
is false.

(Optional) Specifies a maximum size in bytes for a capped collection. If


size number
capped is true, then you need to specify this field also.

(Optional) Specifies the maximum number of documents allowed in the


max number
capped collection.
While inserting the document, MongoDB first checks size field of capped collection, then it
checks max field.
Examples:
Basic syntax of createCollection() method without options is as follows −
>use test
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
>
You can check the created collection by using the command show collections.
>show collections
mycollection
system.indexes
The following example shows the syntax of createCollection() method with few important
options −
> db.createCollection("mycol", { capped : true, autoIndexID : true, size : 6142800, max :
10000 } ){
"ok" : 0,
"errmsg" : "BSON field 'create.autoIndexID' is an unknown field.",
"code" : 40415,
"codeName" : "Location40415"
}
>
In MongoDB, you don't need to create collection. MongoDB creates collection automatically,
when you insert some document.

Gandhinagar Institute of Technology 3161611 AWP


>db.tutorialspoint.insert({"name" : "tutorialspoint"}),
WriteResult({ "nInserted" : 1 })
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>
Exercise:
1. To create a collection in MongoDB, use the createCollection() method
2. Write a program to insert multiple documents using the insertMany() method using
mongodb and nodejs
3. Write a program find a data in collection using findone() in mongodb and nodejs

Review Questions:
1. How do we implement async in Node.js?
2. How would you connect a MongoDB database to Node.js

Gandhinagar Institute of Technology 3161611 AWP

You might also like