0% found this document useful (0 votes)
31 views110 pages

Web Designing - II

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)
31 views110 pages

Web Designing - II

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/ 110

Unit – 1: Introduction to XML

SUCHIKA PATEL
[UNIT – 1: INTRODUCTION TO XML]

UNIT-1: Introduction to XML

XML:
XML stands for Extensible Markup Language. It is a text-based markup
language derived from Standard Generalized Markup Language (SGML).

XML tags identify the data and are used to store and organize the data, rather than
specifying how to display it like HTML tags, which are used to display the data.

1.1 Characteristics of XML and Use of XML:


Characteristics of XML
❖ XML is extensible − XML allows you to create your own self-descriptive tags,
or language, that suits your application.

❖ XML carries the data does not present it − XML allows you to store the data
Irrespective of how it will be presented.

❖ XML is a public standard − XML was developed by an organization called the World
Wide Web Consortium (W3C) and is available as an open standard.

XML Usage:

❖ XML can work behind the scene to simplify the creation of HTML documents
for large web sites.

❖ XML can be used to exchange the information between organizations and systems.

❖ XML can be used for offloading and reloading of databases.

❖ XML can be used to store and arrange the data, which can customize your data
handling needs.

❖ XML can easily be merged with style sheets to create almost any desired output.

❖ Virtually, any type of data can be expressed as an XML document.

2 Prepared By: SUCHIKA PATEL


SDJ International College, Palsana.
[UNIT – 1: INTRODUCTION TO XML]

What is Markup?

XML is a markup language that defines set of rules for encoding documents in a
format that is both human-readable and machine-readable.

So what exactly is a markup language? Markup is information added to a document that


enhances its meaning in certain ways, in that it identifies the parts and how they relate to
each other.

More specifically, a markup language is a set of symbols that can be placed in the text of a
document to demarcate and label the parts of that document.

Following example shows how XML markup looks, when embedded in a piece of text −

<message>

<text>Hello, world!</text>

</message>

This snippet includes the markup symbols, or the tags such as <message>...</message> and
<text>... </text>.

The tags <message> and </message> mark the start and the end of the XML code fragment.
The tags <text> and </text> surround the text Hello, world!

Is XML a Programming Language?


A programming language consists of grammar rules and its own vocabulary which is
used to create computer programs.

These programs instruct the computer to perform specific tasks. XML does not qualify to be
a programming language as it does not perform any computation or algorithms.

It is usually stored in a simple text file and is processed by special software that is capable of
interpreting XML.

3 Prepared By: SUCHIKA PATEL


SDJ International College, Palsana.
[UNIT – 1: INTRODUCTION TO XML]

1.2 XML - Syntax:


The following diagram depicts the syntax rules to write different types of markup
and text in an XML document.

XML Declaration

The XML document can optionally have an XML declaration. It is written as follows −

<?xml version = "1.0" encoding = "UTF-8"?>

Where version is the XML version and encoding specifies the character encoding used in the
document.

Syntax Rules for XML Declaration

❖ The XML declaration is case sensitive and must begin with "<?xml>" where "xml"
is written in lower-case.

❖ If document contains XML declaration, then it strictly needs to be the first statement
of the XML document.

❖ An HTTP protocol can override the value of encoding that you put in the
XML declaration.

Tags and Elements

An XML file is structured by several XML-elements also called XML-nodes or XML-tags.


The names of XML-elements are enclosed in triangular brackets < > as shown below −

4 Prepared By: SUCHIKA PATEL


SDJ International College, Palsana.
[UNIT – 1: INTRODUCTION TO XML]

<element>

Syntax Rules for Tags and Elements


Element Syntax − Each XML-element needs to be closed either with start or with end
elements as shown below −

<element>. .. </element>

or in simple-cases, just this way −

<element/>

Nesting of Elements − an XML-element can contain multiple XML-elements as its


children, but the children elements must not overlap. i.e., an end tag of an element must
have the same name as that of the most recent unmatched start tag.

The Following example shows incorrect nested tags −

<?xml version = "1.0"?>

<contact-info>

<company>Google

</contact-info>

</company>

The Following example shows correct nested tags −

<?xml version = "1.0"?>

<contact-info>

<company> Google </company>

</contact-info>

1.3 Root Element, Case Sensitivity

Root Elements
Root Elements an XML document can have only one root element. For example, following
is not a correct XML document, because both the x and y elements occur at the top level
without a root element −

5 Prepared By: SUCHIKA PATEL


SDJ International College, Palsana.
[UNIT – 1: INTRODUCTION TO XML]

<x>. </x>

<y>. </y>

The Following example shows a correctly formed XML document −

<root>

<x>. </x>
<y>...</y>

</root>

Case Sensitivity –
The names of XML-elements are case-sensitive. That means the name of the start and the
end elements need to be exactly in the same case.

For example, <contact-info> is different from <Contact-

Info> XML Attributes

An attribute specifies a single property for the element, using a name/value pair. An XML-
element can have one or more attributes. For example −

<a href = "http://www.tutorialspoint.com/">Tutorialspoint!</a>

Here href is the attribute name and http://www.tutorialspoint.com/ is attribute value.

Syntax Rules for XML Attributes

❖ Attribute names in XML (unlike HTML) are case sensitive. That is, HREF and href
are considered two different XML attributes.

❖ Same attribute cannot have two values in syntax. The following example shows
incorrect syntax because the attribute b is specified twice

<a b = "x" c = "y" b = "z"> </a>

❖ Attribute names are defined without quotation marks, whereas attribute values must
always appear in quotation marks. Following example demonstrates incorrect xml
syntax

<a b = x>. . </a>

In the above syntax, the attribute value is not defined in quotation marks.

XML References

6 Prepared By: SUCHIKA PATEL


SDJ International College, Palsana.
[UNIT – 1: INTRODUCTION TO XML]

References usually allow you to add or include additional text or markup in an XML
document. References always begin with the symbol "&" which is a reserved character and
end with the symbol ";". XML has two types of references −

❖ Entity References − an entity reference contains a name between the start and the
end delimiters. For example &amp; where amp is name. The name refers to a
predefined string of text and/or markup.

❖ Character References − These contain references, such as &#65;, contains a hash


mark (“#”) followed by a number. The number always refers to the Unicode code of
a character. In this case, 65 refers to alphabet "A".

XML Text

The names of XML-elements and XML-attributes are case-sensitive, which means the name
of start and end elements need to be written in the same case. To avoid character encoding
problems, all XML files should be saved as Unicode UTF-8 or UTF-16 files.

Whitespace characters like blanks, tabs and line-breaks between XML-elements and
between the XML-attributes will be ignored.

Some characters are reserved by the XML syntax itself. Hence, they cannot be used directly.
To use them, some replacement-entities are used, which are listed below −

Not Allowed Replacement Character


Character Entity Description
< &lt; less than

> &gt; greater than

& &amp; ampersand

' &apos; apostrophe

" &quot; quotation mark

7 Prepared By: SUCHIKA PATEL


SDJ International College, Palsana.
[UNIT – 1: INTRODUCTION TO XML]

1.4 XML – Documents


An XML document can contains wide variety of data. For example, database of
numbers, numbers representing molecular structure or a mathematical equation.

A simple document is shown in the following example −

<?xml version = "1.0"?>

<contact-info>

<name>Tanmay Patil</name>

<company>TutorialsPoint</company>

<phone>(011) 123-4567</phone>

</contact-info>

The following image depicts the parts of XML document.

1.4.1 Document Prolog Section


Document Prolog comes at the top of the document, before the root element. This
Section contains −

❖ XML declaration

❖ Document type declaration

1.4.2 Document Elements Section


Document Elements are the building blocks of XML. These divide the document
into a hierarchy of sections, each serving a specific purpose.

You can separate a document into multiple sections so that they can be rendered
differently, or used by a search engine.

The elements can be containers, with a combination of text and other elements.
8 Prepared By: SUCHIKA PATEL
SDJ International College, Palsana.
[UNIT – 1: INTRODUCTION TO XML]

1.5 XML Declaration and rules of declaration


XML – Declaration
XML declaration contains details that prepare an XML processor to parse the
XML document. It is optional, but when used, it must appear in the first line of the
XML document.

Syntax
Following syntax shows XML declaration −

<?xml

version = "version_number"

encoding = "encoding_declaration"

standalone = "standalone_status"
?>

Each parameter consists of a parameter name, an equals sign (=), and parameter value
inside a quote. Following table shows the above syntax in detail −
Parameter Parameter_value Parameter_description

Specifies the version of the XML


Version 1.0 standard used.

UTF-8, UTF-16, ISO-


10646-UCS-2, ISO-
10646- UCS-4, ISO-
8859-1 to It defines the character encoding used in
Encoding ISO-8859-9, ISO-2022- the document. UTF-8 is the default
JP, encoding used.
Shift_JIS, EUC-JP
It informs the parser whether the
document relies on the information
from an external source, such as
external document type definition
(DTD), for its content. The default value
is set to no. Setting it to yes tells the
Standalone yes or no
processor there are no external
declarations required for parsing the
document.

9 Prepared By: SUCHIKA PATEL


SDJ International College, Palsana.
[UNIT – 1: INTRODUCTION TO XML]

Rules:
An XML declaration should abide with the following rules −

❖ If the XML declaration is present in the XML, it must be placed as the first line in
the XML document.

❖ If the XML declaration is included, it must contain version number attribute.

❖ The Parameter names and values are case-sensitive.

❖ The names are always in lower case.

❖ The order of placing the parameters is important. The correct order is: version,
encoding and standalone.

❖ Either single or double quotes may be used.

❖ The XML declaration has no closing tag i.e. </?xml>

XML Declaration Examples

Following are few examples of XML declarations

− XML declaration with no parameters −

<?xml >

XML declaration with version definition −

<?xml version = "1.0">

XML declaration with all parameters defined −

<?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?>

XML declaration with all parameters defined in single quotes −

<?xml version = '1.0' encoding = 'iso-8859-1' standalone = 'no' ?>

10 Prepared By: SUCHIKA PATEL


SDJ International College, Palsana.
UNIT: 2 jQuery Fundamentals

SUCHIKA PATEL
UNIT: 2 jQuery Fundamentals

Unit-2: jQuery Fundamentals:


2.1 Introduction and basics:
o jQuery is a small, fast and lightweight JavaScript library.
o jQuery is platform-independent.
o jQuery means "write less do more".
o jQuery simplifies AJAX call and DOM manipulation

jQuery Features

o HTML manipulation
o DOM manipulation
o DOM element selection
o CSS manipulation
o Effects and Animations
o Utilities
o AJAX
o HTML event methods
o JSON Parsing
o Extensibility through plug-ins

Many of the biggest companies on the web use jQuery.

Some of these companies are:

o Microsoft
o Google
o IBM
o Netflix

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

❖ Jquery History
o jQuery was first released in January 2006 by John Resig at BarCamp
NYC. It is currently headed by Timmy Wilson and maintained by a team
of developers.
o Nowadays, jQuery is widely used technology. Most of the websites are
using jQuery.

2.1.1 Advantage of jQuery and Syntax

Advantages of JQuery

➢ Wide range of plug-ins. jQuery allows developers to create plug-ins on


top of the JavaScript library.
➢ Large development community
➢ It has a good and comprehensive documentation
➢ It is a lot more easy to use compared to standard javascript and other
javascript libraries.
➢ JQuery lets users develop Ajax templates with ease, Ajax enables a
sleeker interface where actions can be performed on pages without
requiring the entire page to be reloaded.
➢ Being Light weight and a powerful chaining capabilities makes jQuery
more strong.

JQuery Syntax:

$(selector).action()

➢ A $ sign is to define/access jQuery


➢ A (selector) is to “query (or find)” HTML elements in html page
➢ A jQuery action() is the action to be performed on the selected element(s)

2.1.2 jQuery Selectors:

• jQuery selectors allow you to select and manipulate HTML element(s).

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

• jQuery selectors are used to "find" (or select) HTML elements based on
their name, id, classes, types, attributes, values of attributes and much
more. It's based on the existing CSS Selectors, and in addition, it has
some own custom selectors.

• All selectors in jQuery start with the dollar sign and parentheses: $().

• The element Selector


• The jQuery element selector selects elements based on the element name.

• You can select all <p> elements on a page like this:


• $("p")

Example :

$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});

The #id Selector

• The jQuery #id selector uses the id attribute of an HTML tag to find the
specific element.

• An id should be unique within a page, so you should use the #id selector
when you want to find a single, unique element.

• To find an element with a specific id, write a hash character, followed by


the id of the HTML element:

• $("#test")
• Example

• When a user clicks on a button, the element with id="test" will be hidden:

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});

The .class Selector

• The jQuery .class selector finds elements with a specific class.

• To find elements with a specific class, write a period character, followed


by the name of the class:

• $(".test")
Example

When a user clicks on a button, the elements with class="test" will be hidden:

$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});

Syntax Description

$("*") Selects all elements

$(this) Selects the current HTML element

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

$("p.intro") Selects all <p> elements with class="intro"

$("p:first") Selects the first <p> element

$("ul li:first") Selects the first <li> element of the first <ul>

$("ul li:first-child") Selects the first <li> element of every <ul>

$("[href]") Selects all elements with an href attribute

$("a[target='_blank']") Selects all <a> elements with a target


attribute value equal to "_blank"

$("a[target!='_blank']") Selects all <a> elements with a target


attribute value NOT equal to "_blank"

$(":button") Selects all <button> elements and <input>


elements of type="button"

$("tr:even") Selects all even <tr> elements

$("tr:odd") Selects all odd <tr> elements

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

2.1.3 jQuery Events (ready(),click(), keypress(),focus(),blur(),change())

Event : moment when something happen

Examples:

• moving a mouse over an element


• selecting a radio button
• clicking on an element

➢ The term "fires/fired" is often used with events

❖ Syntax for event methods

$(selector).action()

• A $ sign to define/access jQuery


• A (selector) to "query (or find)" HTML elements
• A jQuery action() to be performed on the element(s)

➢ To assign a click events to all paragraph on a page :

$(“p”).click();

➢ The next step defines what should happen when the event fires. You must
pass a function to the event.

$("p").click(function(){
// action goes here!!
});

1. ready() :

• The $(document).ready() method allows us to execute a function when


the document is fully loaded.

$(document).ready(function(){
// jQuery methods go here...
});

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

• Short method to use ready() event

$(function(){
// jQuery methods go here...
});

2. click()

• The click event occurs when an element is clicked.

• The click() method triggers the click event, or attaches a function to run
when a click event occurs.

Syntax

$(selector).click()
$(selector).click(function)

Example:

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
alert("The Button was clicked.");
});
});
</script>
</head>
<body>
<p><input type="Button" id="btn" name="btn" value="Button"></p>
</body>
</html>

3. keypress()

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

The order of events related to the keypress event:

1.keydown - The key is on its way down


2.keypress - The key is pressed down
3.keyup - The key is released

• The keypress() method triggers the keypress event, or attaches a function


to run when a keypress event occurs.

• The keypress event is similar to the keydown event. The event occurs
when a button is pressed down.

• However, the keypress event is not fired for all keys (e.g. ALT, CTRL,
SHIFT, ESC).
Syntax

$(selector).keypress()

Attach a function to the keypress event:

$(selector).keypress(function)

Example

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script><script src="js/jquery.js"></script>

i = 0;
$(document).ready(function(){
$("input").keypress(function(){
$("span").text(i += 1);
});
});
</script>
</head>
<body>

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

Enter your name: <input type="text">


<p>Keypresses: <span>0</span></p>
</body>
</html>

4. focus()

The focus event occurs when the <input> field gets focus:

• The focus event occurs when an element gets focus (when selected by a
mouse click or by "tab-navigating" to it).

• The focus() method triggers the focus event, or attaches a function to run
when a focus event occurs.

Syntax

$(selector).focus()

Attach a function to the focus event:

$(selector).focus(function)

Example

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("input").focus(function(){
$("span").css("display", "inline").fadeOut(2000);
});
});
</script>
<style>
span {
display: none;
SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

}
</style>
</head>
<body>

<input>

<span>Nice to meet you!</span>


<p>Click in the input field to get focus.</p>

</body>
</html>

5. blur()

• The blur event occurs when the <input> field loses focus

Syntax

$(selector).blur()
Attach a function to the blur event:
$(selector).blur(function)

Example

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>

$(document).ready(function(){
$("input").blur(function(){
alert("This input field has lost its focus.");
});
});
</script>
</head>
<body>

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

Enter your name: <input type="text">


<p>Write something in the input field, and then click outside the field to lose
focus (blur).</p>

</body>
</html>

6. change()

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>

$(document).ready(function(){
$("input").change(function(){
alert("The text has been changed.");
});
});
</script>
</head>
<body>

<input type="text">

<p>Write something in the input field, and then press enter or click outside the
field.</p>

</body>
</html>

2.2 jQuery Effects:


1. Show/Hide
▪ With jQuery, you can hide and show HTML elements with
the hide() and show() methods

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

Syntax:

$(selector).hide(speed,callback);

$(selector).show(speed,callback);
• Speed: optional parameter. Specifies the speed of the hiding/showing,
and can take the following values: "slow", "fast", or milliseconds.

• Callback: optional parameter. Callback is a function to be executed


after hide() or show() method completes.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example of jQuery Show Hide Effects</title>
<script src="js/jquery.js"></script>
<style>
p{
padding: 15px;
background: #F0E68C;
}
</style>
<script>
$(document).ready(function(){
// Hide displayed paragraphs
$("#hide-btn").click(function(){
$("p").hide();
});

// Show hidden paragraphs


$("#show-btn").click(function(){
$("p").show();
});
});
</script>

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

</head>
<body>
<!--button type="button" class="hide-btn" >Hide </button>
<button type="button" class="show-btn">Show</button -->

<button type="button" id="hide-btn" >Hide </button>


<button type="button" id="show-btn">Show</button>

<p>India is my country.</p>
<p>I love my country.</p>
</body>
</html>

2.Fade

• Fade an element in and out of visibility.

jQuery has the following fade methods:


1.fadeIn()
2.fadeOut()
3.fadeToggle()
4.fadeTo()

1.fadeIn()

• The jQuery fadeIn() method is used to fade in a hidden element.

Syntax:

$(selector).fadeIn(speed,callback);

• Speed parameter : optional parameter. Specifies the duration of the


effect.
• It can take the following values: "slow", "fast", or milliseconds.
• The optional callback parameter is a function to be executed after the
fading completes.

2.fadeOut()

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

• The jQuery fadeOut() method is used to fade out a visible element.

Syntax:

$(selector).fadeOut(speed,callback);

• speed parameter : optional parameter. Specifies the duration of the


effect.

• It can take the following values: "slow", "fast", or milliseconds.

• Callback : The optional callback parameter is a function to be executed


after the fading completes.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example of jQuery Fade-In and Fade-Out Effects</title>
<script src="js/jquery.js"></script>
<style>
p{
padding: 15px;
background: #DDA0DD;
}
</style>
<script>
$(document).ready(function(){
// Fadeing out displayed paragraphs
$(".out-btn").click(function(){
$("p").fadeOut();
});

// Fading in hidden paragraphs


$(".in-btn").click(function(){
$("p").fadeIn();
});
});
</script>
SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

</head>
<body>
<button type="button" class="out-btn">Fade Out Paragraphs</button>
<button type="button" class="in-btn">Fade In Paragraphs</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>

3.fadeToggle()

• The jQuery fadeToggle() method display or hide the selected elements by


animating their opacity in such a way that if the element is initially
displayed, it will be fade out; if hidden, it will be fade in (i.e. toggles the
fading effect).

4.fadeTo()

• The jQuery fadeTo() method allows fading to a given opacity (value


between 0 and 1).

Syntax:

$(selector).fadeTo(speed,opacity,callback);

• speed parameter : required. Specifies the duration of the effect.


• It can take the following values: "slow", "fast", or milliseconds.

• opacity parameter : required . In the fadeTo() method specifies fading to


a given opacity (value between 0 and 1).

• callback :optional parameter,. It is a function to be executed after the


function completes.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

<title>Example of jQuery Fade-Toggle Effect</title>


<script src="js/jquery.js"></script>
<style>
p{
padding: 15px;
background: #DDA0DD;
}
</style>
<script>
$(document).ready(function(){
// Toggles paragraphs display with fading
$(".toggle-btn").click(function(){
$("p").fadeToggle();
});
});
</script>
</head>
<body>
<button type="button" class="toggle-btn">Fade Toggle Paragraphs</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>

• Similarly, you can specify the duration parameter for the fadeToggle()
method like fadeIn()/fadeOut() method to control the duration or speed of
the fade toggle animation.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example of jQuery Fade-Toggle Effect with Different Speeds</title>
<script src="js/jquery.js"></script>
<style>
p{
padding: 15px;
background: #DDA0DD;
}

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

</style>
<script>
$(document).ready(function(){
// Fade Toggles paragraphs with different speeds
$(".toggle-btn").click(function(){
$("p.normal").fadeToggle();
$("p.fast").fadeToggle("fast");
$("p.slow").fadeToggle("slow");
$("p.very-fast").fadeToggle(50);
$("p.very-slow").fadeToggle(2000);
});
});
</script>
</head>
<body>
<button type="button" class="toggle-btn">Fade Toggle Paragraphs</button>
<p class="very-fast">This paragraph will fade in/out with very fast
speed.</p>
<p class="normal">This paragraph will fade in/out with default speed.</p>
<p class="fast">This paragraph will fade in/out with fast speed.</p>
<p class="slow">This paragraph will fade in/out with slow speed.</p>
<p class="very-slow">This paragraph will fade in/out with very slow
speed.</p>
</body>
</html>

4.fadeTo()

• The jQuery fadeTo() method allows fading to a given opacity (value


between 0 and 1).

Syntax:

$(selector).fadeTo(speed,opacity,callback);

• speed parameter : required. Specifies the duration of the effect.


• It can take the following values: "slow", "fast", or milliseconds.

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

• opacity parameter : required . In the fadeTo() method specifies fading to


a given opacity (value between 0 and 1).

• callback :optional parameter,. It is a function to be executed after the


function completes.

Result Size: 753 x 599


<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeTo("slow", 0.15);
$("#div2").fadeTo("slow", 0.4);
$("#div3").fadeTo("slow", 0.7);
});
});
</script>
</head>
<body>

<p>Demonstrate fadeTo() with different parameters.</p>

<button>Click to fade boxes</button><br><br>

<div id="div1" style="width:80px;height:80px;background-


color:red;"></div><br>
<div id="div2" style="width:80px;height:80px;background-
color:green;"></div><br>
<div id="div3" style="width:80px;height:80px;background-color:blue;"></div>

</body>
</html>

3.Slide

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

With jQuery you can create a sliding effect on elements.

jQuery has the following slide methods:

1.slideDown()

The jQuery slideDown() method is used to slide down an element.

Syntax:

$(selector).slideDown(speed,callback);

• The optional speed parameter specifies the duration of the effect. It can
take the following values: "slow", "fast", or milliseconds.

• The optional callback parameter is a function to be executed after the


sliding completes.

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown("slow");
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}

#panel {
padding: 50px;
SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

display: none;
}
</style>
</head>
<body>

<div id="flip">Click to slide down panel</div>


<div id="panel">Hello world!</div>

</body>
</html>

2.slideUp()

jQuery slideUp() Method


The jQuery slideUp() method is used to slide up an element.

Syntax:

$(selector).slideUp(speed,callback);

• The optional speed parameter specifies the duration of the effect. It can
take the following values: "slow", "fast", or milliseconds.

• The optional callback parameter is a function to be executed after the


sliding completes.
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideUp("slow");
});
});
</script>
<style>
#panel, #flip {
padding: 5px;

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}

#panel {
padding: 50px;
}
</style>
</head>
<body>

<div id="flip">Click to slide up panel</div>


<div id="panel">Hello world!</div>

</body>
</html>

3.slideToggle()

• The jQuery slideToggle() method toggles between the slideDown() and


slideUp() methods.

• If the elements have been slid down, slideToggle() will slide them up.

• If the elements have been slid up, slideToggle() will slide them down.

Syntax

$(selector).slideToggle(speed,callback);

• The optional speed parameter can take the following values: "slow",
"fast", milliseconds.

• The optional callback parameter is a function to be executed after the


sliding completes.

<!DOCTYPE html>
<html>
SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

<head>
<script src="js/jquery.js"></script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}

#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>

<div id="flip">Click to slide the panel down or up</div>


<div id="panel">Hello world!</div>

</body>
</html>

4.Stop

• The jQuery stop() method is used to stop animations or effects before it is


finished.
• The stop() method works for all jQuery effect functions, including
sliding, fading and custom animations.

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

Syntax:

$(selector).stop(stopAll,goToEnd);

• The optional stopAll parameter specifies whether also the animation


queue should be cleared or not. Default is false, which means that only
the active animation will be stopped, allowing any queued animations to
be performed afterwards.

• The optional goToEnd parameter specifies whether or not to complete


the current animation immediately. Default is false.

• By default, the stop() method kills the current animation being performed
on the selected element.

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown(5000);
});
$("#stop").click(function(){
$("#panel").stop();
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
font-size: 18px;
text-align: center;
background-color: #555;
color: white;
border: solid 1px #666;
border-radius: 3px;
}

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>

<button id="stop">Stop sliding</button>

<div id="flip">Click to slide down panel</div>


<div id="panel">Hello world!</div>

</body>
</html>

5.Chaining

• Chaining allows us to run multiple jQuery methods (on the same element)
within a single statement.
• chaining is a technique that allows us to run multiple jQuery commands,
one after the other, on the same element(s).
• To chain an action, you simply append the action to the previous action.

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
$(document).ready(function(){
$("button").click(function(){
$("#p1").css("color", "red").slideUp(2000).slideDown(2000);
});
});
</script>
</head>
<body>
<p id="p1">jQuery is fun!!</p>
<button>Click here</button>

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

</body>
</html>

6.Callback

• JavaScript statements are executed line by line. However, with effects,


the next line of code can be run even though the effect is not finished.
This can create errors.
• To prevent this, you can create a callback function.
• A callback function is executed after the current effect is finished.

syntax:

$(selector).hide(speed,callback);

Example with callback

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>

$(document).ready(function(){
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
});
</script>
</head>
<body>
<button>Hide</button>
<p>This is a paragraph with little content.</p>
</body>
</html>

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

Example without callback

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide(1000);
alert("The paragraph is now hidden");
});
});
</script>
</head>
<body>
<button>Hide</button>
<p>This is a paragraph with little content.</p>
</body>
</html>

2.3 jQuery Manipulation methods:

• This methods are use to assign or to read some value on a selection.


• When these methods are called with no argument, it is referred to as a
getters, because it gets (or reads) the value of the element. When these
methods are called with a value as an argument, it's referred to as a setter
because it sets (or assigns) that value.

2.3.1 Get/Set methods (text(), attr(), html(), val())

1. text()

• This method is either used to get the combined text contents of the
selected elements, including their descendants, or set the text contents of
the selected elements.

Example GET method

<!DOCTYPE html>

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Text Contents of the Elements</title>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$(".btn-one").click(function(){
var str = $("p").text();
alert(str);
});
$(".btn-two").click(function(){
var str = $("p:first").text();
alert(str);
});
$(".btn-three").click(function(){
var str = $("p.extra").text();
alert(str);
});
});
</script>
</head>
<body>
<button type="button" class="btn-one">Get All Paragraph's Text</button>
<button type="button" class="btn-two">Get First Paragraph's Text</button>
<button type="button" class="btn-three">Get Last Paragraph's Text</button>

<p>para1 : Hello Students</p>


<p>Para 2 : Good Morning</p>
<p class="extra">Para 3 : Happy Learning</p>
</body>
</html>

Example SET method

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

<title>jQuery Set Text Contents of the Elements</title>


<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$(".btn-one").click(function(){
$("p").text("This is demo text.");
});
$(".btn-two").click(function(){
$("p:first").text("This is another demo text.");
});
$(".btn-three").click(function(){
$("p.empty").text("This is one more demo text.");
});
});
</script>
</head>
<body>
<button type="button" class="btn-one">Set All Paragraph's
Text</button>
<button type="button" class="btn-two">Set First Paragraph's
Text</button>
<button type="button" class="btn-three">Set Empty Paragraph's
Text</button>
<p>Paragraph 1</p>
<p>Paragraph 2.</p>
<p class="empty"></p>
</body>
</html>

2. attr()

• attr() method to either get the value of an element's attribute or set


one or more attributes for the selected element.

Get Attribute Value with attr() Method


• The following example will show you how get the href attribute of the
hyperlink
• i.e. the <a> element as well as the alt attribute of an <img> element:
<!DOCTYPE html>

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get an Element's Attribute Value</title>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$(".btn-one").click(function(){
var str = $("a").attr("href");
alert(str);
});
$(".btn-two").click(function(){
var str = $("img#sky").attr("alt");
alert(str);
});
});
</script>
</head>
<body>
<button type="button" class="btn-one">Get Link's HREF Attribute</button>
<button type="button" class="btn-two">Get Image ALT Attribute</button>
<p><a href="https://www.google.com/">Google search engine</a></p>
<img id="sky" src="/examples/images/sky.jpg" alt="Cloudy Sky">
</body>
</html>

3. html()

• The jQuery html() method is used to get or set the HTML contents of the
elements.
• Get HTML Contents with html() Method

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get HTML Contents of an Element</title>
<script src="js/jquery.js"></script>
<script>
SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

$(document).ready(function(){
$(".btn-one").click(function(){
var str = $("p").html();
alert(str);
});
$(".btn-two").click(function(){
var str = $("#container").html();
alert(str);
});
});
</script>
</head>
<body>
<button type="button" class="btn-one">Get Paragraph's HTML
Contents</button>
<button type="button" class="btn-two">Get Container's HTML
Contents</button>
<div id="container">
<h1>Hello World!</h1>
<p>The quick <b>brown fox</b> jumps over the lazy dog.</p>
</div>
</body>
</html>

Set HTML Contents with html() Method

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Set HTML Contents of the Element</title>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("body").html("<p>Hello World!</p>");
});
SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

});
</script>
</head>
<body>
<button type="button">Write Message</button>
</body>
</html>

Set Attributes with attr() Method

The following example will show you how to set the checked attribute of
the checkbox.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Set Element's Attribute Value</title>
<script src="js/jquery.js"></script>

<script>
$(document).ready(function(){
$("button").click(function(){
$('input[type="checkbox"]').attr("checked", "checked");
});
});
</script>
</head>
<body>
<p><label><input type="checkbox"></label> I agree with terms and
conditions.</p>
<button type="button">Check</button>
</body>
</html>
• The attr() method also allows you to set multiple attributes at a time.

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

• The following example will show you how to set the class and title
attribute for the <img> elements.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Set Multiple Attribute for the Elements</title>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("img").attr({
"class" : "frame",
"title" : "Hot Air Balloons"
});
});
});
</script>
<style>
.frame{
border: 6px solid #000;
}
</style>
</head>
<body>
<button type="button">Set Attributes for Image</button>
<p>
<img src="/examples/images/balloons.jpg" alt="Hot Air Balloons">
</p>
</body>
</html>

jQuery val() Method

• The jQuery val() method is mainly used to get or set the current value of
the HTML form elements such as <input>, <select> and <textarea>.

• Get the Values of Form Fields with val() Method

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get a Form Field Value</title>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button.get-name").click(function(){
var name = $("#name").val();
alert(name);
});
$("button.get-comment").click(function(){
var comment = $("#comment").val();
alert(comment);
});
$("button.get-city").click(function(){
var city = $("#city").val();
alert(city);
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td>Name:</td>
<td>
<input type="text" id="name">
</td>
</tr>
<tr>
<td>Comments:</td>
<td>
<textarea rows="4" cols="30" id="comment"></textarea>
SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

</td>
</tr>
<tr>
<td>City:</td>
<td>
<select id="city">
<option>London</option>
<option>Paris</option>
<option>New York</option>
</select>
</td>
</tr>
</table>
</form>
<p><strong>Note:</strong> Fill the above form and click the following
button to get the value.</p>
<button type="button" class="get-name">Get Name</button>
<button type="button" class="get-comment">Get Comment</button>
<button type="button" class="get-city">Get City</button>
</body>
</html>

Set the Values of Form Fields with val() Method


The following example will show you how to set the values of the form
controls:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Set Form Fields Values</title>
<script src="js/jquery.js"></script>

<script>
$(document).ready(function(){
$("button").click(function(){
var text = $(this).text();
$('input[type="text"]').val(text);

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

});
});
</script>
</head>
<body>
<button type="button">Discovery</button>
<button type="button">Atlantis</button>
<button type="button">Endeavour</button>
<p><strong>Note:</strong> Click the above buttons to set the value of
following input box.</p>
<p>
<input type="text">
</p>
</body>
</html>

2.3.2 Inert methods: (append(), prepend(),text(), before(), after(), wrap())


1. append()

• The append() method inserts specified content at the end of the


selected elements.

Syntax
$(selector).append(content,function(index,html))

Parameter Description

content Required. Specifies the content to insert (can contain


HTML tags)

Possible values:

• HTML elements
• jQuery objects
• DOM elements

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

function(index,html) Optional. Specifies a function that returns the content


to insert

• index - Returns the index position of the


element in the set
• html - Returns the current HTML of the selected
element

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").append(" <b>Appended text</b>.");
});
$("#btn2").click(function(){
$("ol").append("<li>Appended item</li>");
});
});
</script>
</head>
<body>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>

<button id="btn1">Append text</button>


<button id="btn2">Append list item</button>

</body>
</html>
SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

*** append text with function

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").append(function(n){
return "<b>This p element has index " + n + ".</b>";
});
});
});
</script>
</head>
<body>

<h1>This is a heading</h1>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Insert content at the end of each p element</button>

</body>
</html>

2. prepend()

• The prepend() method inserts specified content at the beginning of the


selected elements.
Syntax
$(selector).prepend(content,function(index,html))

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

Parameter Description

content Required. Specifies the content to insert (can contain


HTML tags)

Possible values:

• HTML elements
• jQuery objects
• DOM elements

function(index,html) Optional. Specifies a function that returns the content


to insert

• index - Returns the index position of the


element in the set
• html - Returns the current HTML of the selected
element

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").prepend("<b>Prepended text</b>. ");
});
$("#btn2").click(function(){
$("ol").prepend("<li>Prepended item</li>");
});
});
</script>
</head>
<body>

<p>This is a paragraph.</p>
SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

<p>This is another paragraph.</p>

<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>

<button id="btn1">Prepend text</button>


<button id="btn2">Prepend list item</button>

</body>
</html>

Example with function

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").prepend(function(n){
return "<b>This p element has index " + n + "</b>. ";
});
});
});
</script>
</head>
<body>

<h1>This is a heading</h1>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Insert content at the beginning of each p element</button>

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

</body>
</html>

3. text()

• Get the combined text contents of each element in the set of matched
elements, including their descendants.
• This method does not accept any arguments.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>text demo</title>
<style>
p{
color: blue;
margin: 8px;
}
b{
color: red;
}
</style>
<script src="js/jquery.js"></script>
</head>
<body>

<p><b>Test</b> Paragraph.</p>
<p></p>

<script>
var str = $( "p" ).first().text();
$( "p" ).last().html( str );
</script>

</body>
</html>

4. before()

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

• The before() method inserts specified content in front of (before) the


selected elements.

Syntax

$(selector).before(content,function(index))

Parameter Description

content Specifies the content to insert (can contain HTML tags)

Possible values:

• HTML elements
• jQuery objects
• DOM elements

function(index) Optional. Specifies a function that returns the content to


insert

• index - Returns the index position of the element in


the set

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
function beforeText() {
var txt1 = "<b>I </b>"; // Create element with HTML
var txt2 = $("<i></i>").text("love "); // Create with jQuery
var txt3 = document.createElement("b"); // Create with DOM
txt3.innerHTML = "jQuery!";
$("img").before(txt1, txt2, txt3); // Insert new elements before img
}

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

</script>
</head>
<body>

<img src="/images/w3jquery.gif" alt="jQuery" width="100" height="140">

<p>Click the button to insert text before the image.</p>

<button onclick="beforeText()">Insert before</button>

</body>
</html>

Example 2 :

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").before(function(n){
return "<div>The p element below has index " + n + ".</div>";
});
});
});
</script>
</head>
<body>

<h1>This is a heading</h1>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p>This is another paragraph.</p>

<button>Insert content before each p element</button>

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

</body>
</html>

5. after()

The after() method inserts specified content after the selected elements.

Syntax

$(selector).after(content,function(index))

Parameter Description

content Required. Specifies the content to insert (can contain HTML


tags)

Possible values:

• HTML elements
• jQuery objects
• DOM elements

function(index) Specifies a function that returns the content to insert

• index - Returns the index position of the element in


the set

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

$("p").after("<p>Hello world!</p>");
});
});
</script>
</head>
<body>

<button>Insert content after each p element</button>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

</body>
</html>

6. wrap()

Wrap a <div> element around each <p> element

Syntax

$(selector).wrap(wrappingElement,function(index))

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").wrap("<div></div>");
});
});
</script>
<style>

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

div{background-color: yellow;}
</style>
</head>
<body>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Wrap a div element around each p element</button>

</body>
</html>

2.3.3 Remove element methods : (remove(),empty(),unwrap())

1. remove()

The remove() method removes the selected elements, including all text and
child nodes.

This method also removes data and events of the selected elements.

Syntax

$(selector).remove(selector)

Parameter Description

selector Optional. Specifies one or more elements to be


removed.
To remove multiple elements, separate them with a
comma (,)

<!DOCTYPE html>
<html>

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").remove();
});
});
</script>
</head>
<body>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Remove all p elements</button>

</body>
</html>

2. empty()
• The empty() method removes all child nodes and content from the
selected elements.

Syntax

$(selector).empty()

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").empty();
});
});
</script>

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

</head>
<body>

<div style="height:100px;background-color:yellow">
This is some text
<p>This is a paragraph inside the div.</p>
</div>

<p>This is a paragraph outside the div.</p>

<button>Remove content of the div element</button>

</body>
</html>

3. unwrap()

The unwrap() method removes the parent element of the selected elements.

Syntax

$(selector).unwrap()

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").unwrap();
});
});
</script>
<style>
div{background-color: yellow;}
article{background-color: pink;}
</style>
</head>

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

<body>

<div>
<p>This is a paragraph inside a div element.</p>
</div>

<article>
<p>This is a paragraph inside an article element.</p>
</article>

<button>Remove the parent element of each p element</button>

</body>
</html>

2.3.4 jQuery Get and Set CSS properties using css() method.

• The css() method sets or returns one or more style properties for the
selected elements.

Return a CSS Property


To return the value of a specified CSS property

syntax:

css("propertyname");
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Background color = " + $("p").css("background-color"));
});
SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p style="background-color:#ff0000">This is a paragraph.</p>


<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>

<button>Return background-color of p</button>

</body>
</html>

• To set a specified CSS property

syntax:

css("propertyname","value");
The following example will set the background-color value for ALL matched
elements:

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").css("background-color", "yellow");
});
});
</script>
</head>
<body>

<h2>This is a heading</h2>
SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

<p style="background-color:#ff0000">This is a paragraph.</p>


<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>

<p>This is a paragraph.</p>

<button>Set background-color of p</button>

</body>
</html>

• Set Multiple CSS Properties


• To set multiple CSS properties

syntax:

css({"propertyname":"value","propertyname":"value",...});

Result Size: 753 x 599


<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


UNIT: 2 jQuery Fundamentals

$("p").css({"background-color": "yellow", "font-size": "200%"});


});
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p style="background-color:#ff0000">This is a paragraph.</p>


<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>

<p>This is a paragraph.</p>

<button>Set multiple styles for p</button>

</body>
</html>

SDJ INTERNATIONAL COLLEGE,PALSANA

Prepared By: SUCHIKA PATEL 1


Unit - 3

[JSON-JAVASCRIPT OBJECT NOTATION]

Prof.SUCHIKA PATEL
Unit - 3 [JSON]

3. JSON (JavaScript Object Notation)

JSON:
JSON or JavaScript Object Notation is a lightweight text-based open standard
designed for human-readable data interchange. Conventions used by JSON are known to
programmers, which include C, C++, Java, Python, Perl, etc.

• JSON stands for JavaScript Object Notation.

• The format was specified by Douglas Crockford.

• It was designed for human-readable data interchange.

• It has been extended from the JavaScript scripting language.

• The filename extension is .json.

• JSON Internet Media type is application/json.

• The Uniform Type Identifier is public.json.

Uses of JSON

• It is used while writing JavaScript based applications that includes browser


extensions and websites.

• JSON format is used for serializing and transmitting structured data over network
connection.

• It is primarily used to transmit data between a server and web applications.

• Web services and APIs use JSON format to provide public data.

• It can be used with modern programming languages.

Characteristics of JSON

• JSON is easy to read and write.

• It is a lightweight text-based interchange format.

• JSON is language independent.

Simple Example in JSON


Prepared By: SUCHIKA PATEL 2
SDJ International College,Palsana.
Unit - 3 [JSON]

The following example shows how to use JSON to store information related to books based
on their topic and edition.

"book": [

"id":"01",

"language": "Java",

"edition": "third",

"author": "Herbert Schildt"

},

"id":"07",

"language": "C++",

"edition": "second",

"author": "E.Balagurusamy"

Json.html

<html>
<head>
<title>JSON example</title>
<script language = "javascript" >
var object1 = { "language" : "Java", "author" :
"herbert schildt" };
document.write("<h1>JSON with JavaScript
example</h1>");
document.write("<br>");
document.write("<h3>Language = " +
object1.language+"</h3>");
document.write("<h3>Author = " +
Prepared By: SUCHIKA PATEL 3
SDJ International College,Palsana.
Unit - 3 [JSON]

object1.author+"</h3>");

var object2 = { "language" : "C++", "author" : "E-


Balagurusamy" };
document.write("<br>");
document.write("<h3>Language = " +
object2.language+"</h3>");
document.write("<h3>Author = " +
object2.author+"</h3>");

document.write("<hr />");
document.write(object2.language + " programming
language can be studied " + "from book written by " +
object2.author);
document.write("<hr />");
</script>
</head>

<body>
</body>
</html>

Comparison with XML


JSON and XML are human readable formats and are language independent. They both have
support for creation, reading and decoding in real world situations. We can compare JSON with XML,
based on the following factors −

Similarities between the json and XML:-

o Self-describing: Both json and xml are self-describing as both xml data and json data
are human-readable text.

o Hierarchical: Both json and xml support hierarchical structure. Here hierarchical
means that the values within values.

o Data interchange format: JSON and XML can be used as data interchange formats by
many different programming languages.

o Parse: Both the formats can be easily parsed.

o Retrieve: Both formats can be retrieved by using HTTP requests. The methods used
for retrieving the data are GET, PUT, POST.

Prepared By: SUCHIKA PATEL 4


SDJ International College,Palsana.
Unit - 3 [JSON]

Differences between the json and XML:-

JSON XML

JSON stands for javascript object XML stands for an extensible markup
notation. language.

The extension of json file is .json. The extension of xml file is .xml.

The internet media type is The internet media type is application/xml or


application/json. text/xml.

The type of format in JSON is The type of format in XML is a markup


data interchange. language.

It is extended from javascript. It is extended from SGML.

It is open source means that we It is also open source.


do not have to pay anything to
use JSON.

The object created in JSON has XML data does not have any type.
some type.

The data types supported by XML data is in a string format.


JSON are strings, numbers,
Booleans, null, array.

It does not have any capacity to XML is a markup language, so it has the
display the data. capacity to display the content.

JSON has no tags. XML data is represented in tags, i.e., start tag
and end tag.

XML file is larger. If we want to represent the


data in XML then it would create a larger file
as compared to JSON.

Prepared By: SUCHIKA PATEL 5


SDJ International College,Palsana.
Unit - 3 [JSON]

JSON is quicker to read and XML file takes time to read and write
write. because the learning curve is higher.

JSON can use arrays to represent XML does not contain the concept of arrays.
the data.

It can be parsed by a standard XML data which is used to interchange the


javascript function. It has to be data, must be parsed with respective to their
parsed before use. programming language to use that.
It can be easily parsed and little It is difficult to parse.
bit code is required to parse the
data.
File size is smaller as compared File size is larger.
to XML.
JSON is data-oriented. XML is document-oriented.

It is less secure than XML. It is more secure than JSON.

JSON Objects
This is a JSON string:

'{"name":"John", "age":30, "car":null}'

Inside the JSON string there is a JSON object literal:

{"name":"John", "age":30, "car":null}

JSON object literals are surrounded by curly braces {}.

JSON object literals contains key/value pairs.

Keys and values are separated by a colon.

Keys must be strings, and values must be a valid JSON data type:

• string

• number

Prepared By: SUCHIKA PATEL 6


SDJ International College,Palsana.
Unit - 3 [JSON]

• object

• array

• boolean

• null

Each key/value pair is separated by a comma.

It is a common mistake to call a JSON object literal "a JSON object".

JSON cannot be an object. JSON is a string format.

The data is only JSON when it is in a string format. When it is converted to a JavaScript
variable, it becomes a JavaScript object.

JavaScript Objects
You can create a JavaScript object from a JSON object literal:

Example

myObj = {"name":"John", "age":30, "car":null};

Normally, you create a JavaScript object by parsing a JSON string:

Example

myJSON = '{"name":"John", "age":30, "car":null}';


myObj = JSON.parse(myJSON);

Accessing Object Values

You can access object values by using dot (.) notation:

Example

const myJSON = '{"name":"John", "age":30, "car":null}';


const myObj = JSON.parse(myJSON);
x = myObj.name;

You can also access object values by using bracket ([]) notation:

Example

Prepared By: SUCHIKA PATEL 7


SDJ International College,Palsana.
Unit - 3 [JSON]

const myJSON = '{"name":"John", "age":30, "car":null}';


const myObj = JSON.parse(myJSON);
x = myObj["name"];

Looping an Object

You can loop through object properties with a for-in loop:

Example

const myJSON = '{"name":"John", "age":30, "car":null}';


const myObj = JSON.parse(myJSON);

let text = "";


for (const x in myObj) {
text += x + ", ";
}

In a for-in loop, use the bracket notation to access the property values:

Example

const myJSON = '{"name":"John", "age":30, "car":null}';


const myObj = JSON.parse(myJSON);

let text = "";


for (const x in myObj) {
text += myObj[x] + ", ";
}

Json Arrays
Arrays in JSON are almost the same as arrays in JavaScript.

In JSON, array values must be of type string, number, object, array, boolean or null.

In JavaScript, array values can be all of the above, plus any other valid JavaScript expression,
including functions, dates, and undefined.

Prepared By: SUCHIKA PATEL 8


SDJ International College,Palsana.
Unit - 3 [JSON]

JavaScript Arrays

You can create a JavaScript array from a literal:

Example

myArray = ["Ford", "BMW", "Fiat"];

You can create a JavaScript array by parsing a JSON string:

Example

myJSON = '["Ford", "BMW", "Fiat"]';


myArray = JSON.Parse(myJSON);

Accessing Array Values

You access array values by index:

Example

myArray[0];

Arrays in Objects

Objects can contain arrays:

Example

{
"name":"John",
"age":30,
"cars":["Ford", "BMW", "Fiat"]
}

You access array values by index:

Example

myObj.cars[0];

Prepared By: SUCHIKA PATEL 9


SDJ International College,Palsana.
Unit - 3 [JSON]

Looping Through an Array

You can access array values by using a for in loop:

Example

for (let i in myObj.cars) {


x += myObj.cars[i];
}

Or you can use a for loop:

Example

for (let i = 0; i < myObj.cars.length; i++) {


x += myObj.cars[i];
}

JSON Array of Strings

Example of JSON arrays storing string values.

["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

JSON Array of Numbers

Example of JSON arrays storing number values.

[12, 34, 56, 43, 95]

JSON Array of Booleans

Example of JSON arrays storing boolean values.

[true, true, false, false, true]

JSON Array of Objects

Let's see a simple JSON array example having 4 objects.

{"employees":[

{"name":"Ram", "email":"[email protected]", "age":23},

Prepared By: SUCHIKA PATEL 10


SDJ International College,Palsana.
Unit - 3 [JSON]

{"name":"Shyam", "email":"[email protected]", "age":28},

{"name":"John", "email":"[email protected]", "age":33},

{"name":"Bob", "email":"[email protected]", "age":41}

]}

JSON Comments
JSON doesn't support comments. It is not a standard.

But you can do some tricks such as adding extra attribute for comment in JSON object, for
example:

"employee": {

"name": "Bob",

"salary": 56000,

"comments": "He is a nice man"

Here, "comments" attribute can be treated as comment.

Prepared By: SUCHIKA PATEL 11


SDJ International College,Palsana.
UNIT - 4
[AJAX – ASYNCHRONOUS
JAVASCRIPT AND XML]

Prepared By: Prof. SUCHIKA PATEL


UNIT - 4 [AJAX – ASYNCHRONOUS JAVASCRIPT AND XML]

4. AJAX (Asynchronous JavaScript and XML)

AJAX:
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new
technique for creating better, faster, and more interactive web applications with
the help of XML, HTML, CSS, and Java Script.

 Ajax uses XHTML for content, CSS for presentation, along with
Document Object Model and JavaScript for dynamic content display.

 Conventional web applications transmit information to and from the


sever using synchronous requests. It means you fill out a form, hit
submit, and get directed to a new page with new information from the
server.

 With AJAX, when you hit submit, JavaScript will make a request to
the server, interpret the results, and update the current screen. In the
purest sense, the user would never know that anything was even
transmitted to the server.

 XML is commonly used as the format for receiving server data, although
any format, including plain text, can be used.

 AJAX is a web browser technology independent of web server software.

 A user can continue to use the application while the client


program requests information from the server in the background.

 Intuitive and natural user interaction. Clicking is not required, mouse


movement is a sufficient event trigger.

 Data-driven as opposed to page-driven.

AJAX cannot work independently. It is used in combination with other


technologies to create interactive WebPages.

Prepared By: Prof. SUCHIKA PATEL 2


SDJ International College Palsana.
UNIT - 4 [AJAX – ASYNCHRONOUS JAVASCRIPT AND XML]

JavaScript

• Loosely typed scripting language.


• JavaScript function is called when an event occurs in a page.
• Glue for the whole AJAX operation.

DOM

• API for accessing and manipulating structured documents.


• Represents the structure of XML and HTML documents.

CSS

• Allows for a clear separation of the presentation style from the content
and may be changed programmatically by JavaScript

XMLHttpRequest

• JavaScript object that performs asynchronous interaction with the server.

Synchronous (Classic Web-Application Model)


A synchronous request blocks the client until operation completes i.e.
browser is unresponsive. In such case, javascript engine of the browser
is blocked.

Prepared By: Prof. SUCHIKA PATEL 3


SDJ International College Palsana.
UNIT - 4 [AJAX – ASYNCHRONOUS JAVASCRIPT AND XML]

As you can see in the above image, full page is refreshed at request time and user
is blocked until request completes.

Let's understand it another way.

Asynchronous (AJAX Web-Application Model)


An asynchronous request doesn’t block the client i.e. browser is responsive.
At that time, user can perform another operation also. In such case, JavaScript
engine of the browser is not blocked.

As you can see in the above image, full page is not refreshed at request time
Prepared By: Prof. SUCHIKA PATEL 4
SDJ International College Palsana.
UNIT - 4 [AJAX – ASYNCHRONOUS JAVASCRIPT AND XML]

and user gets response from the ajax engine.

Let's try to understand asynchronous communication by the image given below.

4.2 XMLHttpRequest
An object of XMLHttpRequest is used for asynchronous
communication between client and server.

It performs following operations:

1. Sends data from the client in the background

2. Receives the data from the server

3. Updates the webpage without reloading it.

Properties of XMLHttpRequest object

The common properties of XMLHttpRequest object are as follows:

Prepared By: Prof. SUCHIKA PATEL 5


SDJ International College Palsana.
UNIT - 4 [AJAX – ASYNCHRONOUS JAVASCRIPT AND XML]

Property Description

onReadyStateChange It is called whenever readystate attribute changes. It


mustnot be used with synchronous requests.
readyState represents the state of the request. It ranges from 0 to
4.
0 UNOPENED open() is not called.
1 OPENED open is called but send() is not called.
2 HEADERS_RECEIVED send() is called, and
headers andstatus are available.
3 LOADING Downloading data; responseText
holds thedata.
4 DONE The operation is completed fully.

reponseText returns response as text.

responseXML returns response as XML

Methods of XMLHttpRequest object:

Method Description

void open(method, URL) opens the request specifying get or


post methodand url.

void open(method, URL, async) same as above but specifies


asynchronous or not.
void open(method, URL, async, same as above but specifies
username, password) username andpassword.

void send() sends get request.

void send(string) send post request.

setRequestHeader(header,value) it adds request headers.

Prepared By: Prof. SUCHIKA PATEL 6


SDJ International College Palsana.
UNIT - 4 [AJAX – ASYNCHRONOUS JAVASCRIPT AND XML]

4.3 How AJAX works?


AJAX communicates with the server using XMLHttpRequest object. Let's try
to understand the flow of ajax or how ajax works by the image displayed
below.

As you can see in the above example, XMLHttpRequest object plays a important role.

1. User sends a request from the UI and a javascript call goes to


XMLHttpRequest object.

2. HTTP Request is sent to the server by XMLHttpRequest object.

3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.

4. Data is retrieved.

5. Server sends XML data or JSON data to the XMLHttpRequest callback function.

6. HTML and CSS data is displayed on the browser.

Prepared By: Prof. SUCHIKA PATEL 7


SDJ International College Palsana.
UNIT - 4 [AJAX – ASYNCHRONOUS JAVASCRIPT AND XML]

Example:

<!DOCTYPE html>

<html>

<body>

<div id="demo">

<h1>The XMLHttpRequest Object</h1>

<button type="button" onclick="loadDoc()">Change Content</button>

</div>
<script>

function loadDoc() {

var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {

if (this.readyState == 4 && this.status == 200) {

document.getElementById("demo").innerHTML =

this.responseText;
}
};

xhttp.open("GET", "ajax_info.txt",

true); xhttp.send();

}
</script>
</body>

</html>
Prepared By: Prof. SUCHIKA PATEL 8
SDJ International College Palsana.
UNIT - 4 [AJAX – ASYNCHRONOUS JAVASCRIPT AND XML]

Example 2:

<html>

<body>

<div id="demo">

<h1>The XMLHttpRequest Object</h1>


<button type="button"

onclick="loadDoc('ajax_info.txt', myFunction)">Change Content

</button>

</div>

<script>

function loadDoc(url,

cFunction) { var xhttp;


xhttp=new XMLHttpRequest();

xhttp.onreadystatechange = function() {

if (this.readyState == 4 &&

this.status== 200) { cFunction(this);

};

xhttp.open("GET", url,

true); xhttp.send();
Prepared By: Prof. SUCHIKA PATEL 9
SDJ International College Palsana.
UNIT - 4 [AJAX – ASYNCHRONOUS JAVASCRIPT AND XML]

function myFunction(xhttp) {

document.getElementById("demo").innerHTML =

xhttp.responseText;

</script>

</body>

</html>

Prepared By: Prof. SUCHIKA PATEL 10


SDJ International College Palsana.
UNIT – 5
[NODE.JS]

Prepared By: SUCHIKA PATEL


UNIT – 5 [NODE.JS]

5. Node.js

Node.js is a cross-platform environment and library for running JavaScript applications


which is used to create networking and server-side applications.

5.1 Concept, Working and Features

Node.js is a cross-platform runtime environment and library for running JavaScript


applications outside the browser. It is used for creating server-side and networking web
applications. It is open source and free to use. It can be downloaded from this link
https://nodejs.org/en/

Many of the basic modules of Node.js are written in JavaScript. Node.js is mostly used to run
real-time server applications.

The definition given by its official documentation is as follows:

“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.”

Node.js also provides a rich library of various JavaScript modules to simplify the
development of web applications.

1 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

Features of Node.JS

Following is a list of some important features of Node.js that makes it the first choice of
software architects.

1. Extremely fast: Node.js is built on Google Chrome's V8 JavaScript Engine, so its library is
very fast in code execution.

2. I/O is Asynchronous and Event Driven: All APIs of Node.js library are asynchronous i.e.
non-blocking. So 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. It is also a reason that it is very
fast.

3. Single threaded: Node.js follows a single threaded model with event looping.

4. Highly Scalable: Node.js is highly scalable because event mechanism helps the server to
respond in a non-blocking way.

5. No buffering: Node.js cuts down the overall processing time while uploading audio and
video files. Node.js applications never buffer any data. These applications simply output the
data in chunks.

6. Open source: Node.js has an open source community which has produced many excellent
modules to add additional capabilities to Node.js applications.

7. License: Node.js is released under the MIT license.

5.1.1 Downloading Node.JS

To install and setup an environment for Node.js, you need the following two software
available on your computer:

1. Text Editor.

2. Node.js Binary installable

You can download the latest version of Node.js installable archive file from
https://nodejs.org/en/.

5.2 Setting up Node.JS server (HTTP Server)

5.2.1 Installing On Windows

There are various installers available on https://nodejs.org/en/. The installation files are
available for Windows, Linux, Solaris, MacOS.
2 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

Download the installer for windows by clicking on LTS or Current version button. Here, we
will install the latest version LTS for windows that has long time support. However, you can
also install the Current version which will have the latest features.

After you download the MSI, double-click on it to start the installation as shown below.

3 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

Accept the terms of license agreement.

Choose the location where you want to install.

4 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

Ready to install:

5 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

Verify Installation

Once you install Node.js on your computer, you can verify it by opening the command
prompt and typing node -v. If Node.js is installed successfully then it will display the version
of the Node.js installed on your machine, as shown below.

6 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

5.2.2 Components

A Node.js application consists of the following three important components -

1. Import required modules: The "require" directive is used to load a Node.js module.

2. Create server: You have to establish a server which will listen to client's request similar to
Apache HTTP Server.

3. Read request and return response: Server created in the second step will read HTTP
request made by client which can be a browser or console and return the response.

5.2.2.1 Required modules, Create Server (http.createserver())

Require Modules: Method require() is used to consume modules. It allows you to include
modules in your app. You can add built-in core Node.js modules, community-based modules
(node_modules), and local modules too.

Node.js follows the CommonJS module system, and the built-in require function is the
easiest way to include modules that exist in separate files. The basic functionality of require
is that it reads a JavaScript file, executes the file, and then proceeds to return the exports
object.

var module = require('module_name');

As per above syntax, specify the module name in the require() function. The require()
function will return an object, function, property or any other JavaScript type, depending on
what the specified module returns.

We use the require directive to load the http module and store the returned HTTP instance
into an http variable as follows -block1

var http = require("http");

In the above example, require() function returns an object because http module returns its
functionality as an object, you can then use its properties and methods using dot notation
e.g. http.createServer().
7 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

Create server: In the second component, you have to use created http instance and call
http.createServer() method to create server instance and then bind it at port 8081 using
listen method associated with server instance. Pass it a function with request and response
parameters and write the sample implementation to return "Hello World". Check the
example below: block2

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/');

5.2.2.2 Request and Response

Now combine the block 1 and block 2 and save the file as check.js; while executing the
above it will just create an HTTP server which listens to the port mentioned as 8081 on the
local machine.

8 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

For starting the server, we need to start the command prompt as follows:

Click the start menu and type node.js command prompt. Once the command prompt is
open just move the location where the check.js file is stored.

Once you get the message like server is running at ͙.. , We can just open any browser and
check for the http://127.0.0.1:8081/

Now, if you make any changes in the " check.js" file, you need to again run the "node
check.js" command.

This is how the http server is created and request which are sent over https server are
responded from the port 8081.

9 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

5.3 Built-In Modules

In Node.js, Modules are the blocks of encapsulated code that communicates with an
external application on the basis of their related functionality. Modules can be a single file or
a collection of multiples files/folders. The reason programmers are heavily reliant on
modules is because of their re-usability as well as the ability to break down a complex piece
of code into manageable chunks.

Node.js has many built-in modules that are part of the platform and comes with Node.js
installation. Node Js Core Modules comes with its installation by default. You can use them
as per application requirements. These modules can be loaded into the program by using
the require function.

5.3.1 require () function

The require () function will return a JavaScript type depending on what the particular
module returns.

var module = require('module_name');

The following example demonstrates how to use the Node.js Http module to create a web
server.

var http = require('http');

http.createServer(function (req, res) {

res.writeHead(200, {'Content-Type': 'text/html'});

res.write('Welcome to this page!');

res.end();

}).listen(3000);

In the above example, the require() function returns an object because the Http module
returns its functionality as an object. The function http.createServer() method will be
executed when someone tries to access the computer on port 3000. The res.writeHead()
method is the status code where 200 means it is OK, while the second argument is an object
containing the response headers.

Module Description

OS Module Provides basic operating-system related


utility functions.

10 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

var os = require("os")

Path Module Provides utilities for handling and


transforming file paths.

var path = require("path")

Net Module Provides both servers and clients as


streams. Acts as a network wrapper.

var net = require("net")

DNS Module Provides functions to do actual DNS


lookup as well as to use underlying
operating system name resolution
functionalities.

var dns = require("dns")

5.3.2 User Defined Modules: Create and include

Modules are the collection of JavaScript codes in a separate logical file that can be used in
external applications on the basis of their related functionality. Modules are popular as they
are easy to use and are reusable. Sometimes it is required that, when you are implementing a
Node.js application for a use case, you might want to keep your business logic separately. In
such cases you create a Node.js module with all the required functions in it.

Create Modules (exports)

The module.exports is a special object which is included in every JavaScript file in the
Node.js application by default. The module is a variable that represents the current module,

11 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

and exports is an object that will be exposed as a module. So, whatever you assign to
module.exports will be exposed as a module.

To create a module in Node.js, the exports keyword is used. This keyword tells Node.js that
the function can be used outside the module. A Node.js Module is a .js file with one or more
functions.

The syntax to define a function in Node.js module is

exports.<function_name> = function (argument_1, argument_2, .. argument_N)

/** function body */

};

• exports - is a keyword which tells Node.js that the function is available outside the
module.
• function_name - is the function name using which we can access this function in
other programs.

As mentioned above, exports is an object. So it exposes whatever you assigned to it as a


module. For example, if you assign a string literal then it will expose that string literal as a
module.

The following example exposes simple string message as a module in Message.js.

module.exports = 'Hello world';

Include Modules (require)

Node.js follows the CommonJS module system, and the built-in require function is the
easiest way to include modules that exist in separate files. The basic functionality of require
is that it reads a JavaScript file, executes the file, and then proceeds to return the exports
object. An example module:

Now, import this message module and use it as shown below.

var msg = require('./Messages.js');

console.log(msg);

Run the above example and see the result, as shown below.

C:\> node app.js Hello World

12 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

Export Object

The exports is an object. So, you can attach properties or methods to it. The following
example exposes an object with a string property in Message.js file.

exports.SimpleMessage = 'Hello world';

//or

module.exports.SimpleMessage = 'Hello world';

In the above example, we have attached a property SimpleMessage to the exports object.
Now, import and use this module, as shown below: app.js

var msg = require('./Messages.js');

console.log(msg.SimpleMessage);

In the above example, the require() function will return an object { SimpleMessage : 'Hello
World'} and assign it to the msg variable. So, now you can use msg.SimpleMessage.

Run the above example by writing node app.js in the command prompt and see the output
as shown below.

C:\> node app.js

Hello World

In the same way as above, you can expose an object with function. The following example
exposes an object with the log function as a module: Log.js

module.exports.log = function (msg) {

console.log(msg); };

The above module will expose an object- { log : function(msg){ console.log(msg); } } . Use the
above module as shown below: app.js

var msg = require('./Log.js');

msg.log('Hello World');

Run and see the output in command prompt as shown below.

C:\> node app.js Hello World

You can also attach an object to module.exports, as shown below: data.js

module.exports = {

13 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

firstName: 'James',

lastName: 'Bond'

app.js

var person = require('./data.js');

console.log(person.firstName + ' ' + person.lastName);

Run the above example and see the result, as shown below.

C:\> node app.js James Bond

5.3.3 HTTP module

To make HTTP requests in Node.js, there is a built-in module HTTP in Node.js to transfer
data over the HTTP. To use the HTTP server in node, we need to require the HTTP module.
The HTTP module creates an HTTP server that listens to server ports and gives a response
back to the client. The HTTP core module is a key module to Node.js networking. It is
designed to support many features of the HTTP protocol.

We can create a HTTP server with the help of http.createServer() method. (Ex:testing.js)

var http = require('http'); // Create a server

http.createServer((request, response)=>{ // Sends a chunk of the response body

response.write('Hello World!');

// Signals the server that all of the response headers and body have been sent

response.end();

})

.listen(3000); // Server listening on port 3000

Above code will start the webserver by running the command node testing.js

var http = require('http');

var options = {

host: 'www.amrolicollege.org',

path: '/sports2122',

14 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

method: 'GET'

};

// Making a get request to 'www.amrolicollege.org'

http.request(options, (response) => { // Printing the statusCode

console.log(`STATUS: ${response.statusCode}`);

}).end();

Above example will display the status code of the request made on server.

The HTTP module provides some properties and methods, and some classes.

http.METHODS

This property lists all the HTTP methods supported:

> require('http').METHODS

[ 'ACL', 'BIND', 'CHECKOUT', 'CONNECT', 'COPY', 'DELETE', 'GET', 'HEAD', 'LINK', 'LOCK', 'M-
SEARCH', 'MERGE', 'MKACTIVITY', 'MKCALENDAR', 'MKCOL', 'MOVE', 'NOTIFY', 'OPTIONS',
'PATCH', 'POST', 'PROPFIND', 'PROPPATCH', 'PURGE', 'PUT', 'REBIND', 'REPORT', 'SEARCH',
'SUBSCRIBE', 'TRACE', 'UNBIND', 'UNLINK', 'UNLOCK', 'UNSUBSCRIBE']

http.STATUS_CODES

This property lists all the HTTP status codes and their description:

<img width="599" height="706" src="">> require('http').STATUS_CODES

'100': 'Continue',

'101': 'Switching Protocols',

'102': 'Processing',

'103': 'Early Hints',

'200': 'OK',

'201': 'Created',

'202': 'Accepted',

'203': 'Non-Authoritative Information',

15 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

'204': 'No Content',

'205': 'Reset Content',

'206': 'Partial Content',

'207': 'Multi-Status',

'208': 'Already Reported',

'226': 'IM Used',

'300': 'Multiple Choices',

'301': 'Moved Permanently',

'302': 'Found',

'303': 'See Other',

'304': 'Not Modified',

'305': 'Use Proxy',

'307': 'Temporary Redirect',

'308': 'Permanent Redirect',

'400': 'Bad Request',

'401': 'Unauthorized',

'402': 'Payment Required',

'403': 'Forbidden',

'404': 'Not Found',

'405': 'Method Not Allowed',

'406': 'Not Acceptable',

'407': 'Proxy Authentication Required',

'408': 'Request Timeout',

'409': 'Conflict',

'410': 'Gone',

'411': 'Length Required',

16 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

'412': 'Precondition Failed',

'413': 'Payload Too Large',

'414': 'URI Too Long',

'415': 'Unsupported Media Type',

'416': 'Range Not Satisfiable', '417':

'Expectation Failed',

'418': "I'm a Teapot",

'421': 'Misdirected Request',

'422': 'Unprocessable Entity',

'423': 'Locked',

'424': 'Failed Dependency',

'425': 'Too Early',

'426': 'Upgrade Required',

'428': 'Precondition Required',

'429': 'Too Many Requests',

'431': 'Request Header Fields Too Large',

'451': 'Unavailable For Legal Reasons',

'500': 'Internal Server Error',

'501': 'Not Implemented',

'502': 'Bad Gateway',

'503': 'Service Unavailable',

'504': 'Gateway Timeout',

'505': 'HTTP Version Not Supported',

'506': 'Variant Also Negotiates',

'507': 'Insufficient Storage',

'508': 'Loop Detected',

17 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

'509': 'Bandwidth Limit Exceeded',

'510': 'Not Extended',

'511': 'Network Authentication Required'

http.globalAgent

The http.globalAgent is a global object of the http.Agent class, which is utilized for all the
HTTP client requests by default. It is used to control connections persistence, and reuse for
HTTP clients. Moreover, it is a significant constituent in Node.js HTTP networking.

http methods are described in the next topic.

5.4 Node.JS as Web Server

When you view a webpage in your browser, you are making a request to another computer
on the internet, which then provides you the webpage as a response. That computer you
are talking to via the internet is a web server. A web server receives HTTP requests from a
client, like your browser, and provides an HTTP response, like an HTML page or JSON from
an API. To access web pages of any web application, you need a web server. The web server
will handle all the http requests for the web application e.g IIS is a web server for ASP.NET
web applications and Apache is a web server for PHP or Java web applications.

A lot of software is involved for a server to return a webpage. This software generally falls
into two categories: frontend and backend. Front-end code is concerned with how the
content is presented, such as the color of a navigation bar and the text styling. Back-end
code is concerned with how data is exchanged, processed, and stored. Code that handles
network requests from your browser or communicates with the database is primarily
managed by back-end code.

Node.js allows developers to use JavaScript to write back-end code, even though
traditionally it was used in the browser to write front-end code. Having both the frontend
and backend together like this reduces the effort it takes to make a web server, which is a
major reason why Node.js is a popular choice for writing back-end code.

There are a variety of modules such as the “http” and “request” module, which helps in
processing server related requests in the webserver space. We will have a look at how we
can create a basic web server application using Node js.

Node.js provides capabilities to create your own web server which will handle HTTP
requests asynchronously. You can use IIS or Apache to run Node.js web application but it is
recommended to use Node.js web server.

18 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

5.4.1 createserver (), writehead () method

Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the
Hyper Text Transfer Protocol (HTTP). The HTTP module can create an HTTP server that
listens to server ports and gives a response back to the client. Refer the code below to
understand the concept; filename:helloserver.js

var http=require('http')

var server=http.createServer((function(request,response)

response.writeHead(200,

{"Content-Type" : "text/plain"});

response.end("Hello World\n");

}));

server.listen(8081);

1. The basic functionality of the require function is that it reads a JavaScript file, executes
the file, and then proceeds to return the exports object. So in our case, since we want to use
the functionality of the http module, we use the require function to get the desired
functions from the http module so that it can be used in our application.

2. In this line of code, we are creating a server application which is based on a simple
function. This function is called whenever a request is made to our server application. The
request object can be used to get information about the current HTTP request e.g., url,
request header, and data. The response object can be used to send a response for a current
HTTP request.

3. When a request is received, we are saying to send a response with a header type of ‘200.’
This number is the normal response which is sent in an http header when a successful
response is sent to the client.

4. In the response itself, we are sending the string ‘Hello World.’

5. We are then using the server.listen function to make our server application listen to client
requests on port no 8081. You can specify any available port over here.

Run the above web server by writing node helloserver.js command in command prompt or
terminal window and it will display message of node.js is running of port no. 8081.

19 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

The http.createServer() method includes request and response parameters which is


supplied by Node.js. The request object can be used to get information about the current
HTTP request e.g., url, request header, and data. The response object can be used to send a
response for a current HTTP request.

var http = require('http'); // Import Node.js core module

var server = http.createServer(function (req, res) { //create web server

if (req.url == '/') { //check the URL of the current request

// set response header

res.writeHead(200, { 'Content-Type': 'text/html' });

// set response content

res.write('<html><body><p>This is home Page.</p></body></html>');

res.end();

else if (req.url == "/student") {

res.writeHead(200, { 'Content-Type': 'text/html' });

res.write('<html><body><p>This is student Page.</p></body></html>');

res.end();

else if (req.url == "/admin")

res.writeHead(200, { 'Content-Type': 'text/html' });

res.write('<html><body><p>This is admin Page.</p></body></html>');

res.end();

else

res.end('Invalid Request!');

});

20 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

server.listen(5000); //6 - listen for any incoming requests

console.log('Node.js web server at port 5000 is running..')

5.4.2 Reading Query String, Split Query String

In Node.js, functionality to aid in the accessing of URL query string parameters is built into
the standard library. The built-in url.parse method takes care of most of the heavy lifting for
us. Here is an example script using this handy function and an explanation on how it works:

const http = require('http');

const url = require('url');

http.createServer(function (req, res) {

const queryObject = url.parse(req.url,true).query;

console.log(queryObject);

res.writeHead(200, {'Content-Type': 'text/html'});

res.end('Feel free to add query parameters to the end of the url');

}).listen(8080);

To test this code run node app.js (app.js is name of the file) on the terminal and then go to
your browser and type http://localhost:8080/app.js?foo=bad&baz=foo on the URL bar.

The key part of this whole script is this line: const queryObject =
url.parse(req.url,true).query;. Let's take a look at things from the inside-out. First off, req.url
will look like /app.js?foo=bad&baz=foo. This is the part that is in the URL bar of the browser.
Next, it gets passed to url.parse which parses out the various elements of the URL (NOTE: the
second parameter is a boolean stating whether the method should parse the query
string, so we set it to true). Finally, we access the .query property, which returns us a nice,
friendly JavaScript object with our query string data.

The url.parse() method returns an object which have many key value pairs one of which is
the query object. Some other handy information returned by the method include host,
pathname, search keys.

In the above code:

url.parse(req.url,true).query returns { foo: 'bad', baz: 'foo' }.

url.parse(req.url,true).host returns 'localhost:8080'.

url.parse(req.url,true).pathname returns '/app.js'.

21 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

url.parse(req.url,true).search returns '?foo=bad&baz=foo'.

Parsing with querystring

Another way to access query string parameters is parsing them using the querystring builtin
Node.js module.

This method, however, must be passed just a querystring portion of a url. Passing it the
whole url, like you did in the url.parse example, won't parse the querystrings.

const querystring = require('querystring');

const url = "http://example.com/index.html?code=string&key=12&id=false";

const qs = "code=string&key=12&id=false";

console.log(querystring.parse(qs));

// > { code: 'string', key: '12', id: 'false' }

console.log(querystring.parse(url));

// > { 'http://example.com/index.html?code': 'string', key: '12', id: 'false' }

5.5 File System Module

This module, as the name suggests, enables developers to work with the file system on its
computers. The require() method is used to include the File System module. Some of the
most common uses of this module is to create, read, update, delete, rename or read files.
For example, the function fs.readFile() is used to read files on the computer.

5.5.1 Read files (readFile())

The Node.js file system module (fs module) allows you to work with the files. The
fs.readFile() is used to read from file.

There are two ways to read file

1. Read file Asynchronously:

var fs = require('fs');

fs.readFile('my_file.txt', (err, data) => {

if (err){

throw err;

}else{

22 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

console.log("Content of file is: " + data);

});

2. Read file synchronously:

var fs = require('fs');

var filename = 'my_file.txt';

var content = fs.readFileSync(filename);

console.log('Content of file is: ' + content);

5.5.2 Create Files (appendFile(), open (), writeFile())

There are a bunch of methods used for creating new files are: fs.appendFile (), fs.open (),
fs.writeFile ().

The append method is used to, as the name suggests, append the given file. Also, if one
particular file is appended but does not exist then a file of the same name will be created.
The syntax of fs.appendFile () would look something like -

fs.appendFile('newfile.txt', 'Hello Konfinity!', function (err) { if

(err) throw err;

console.log('Done!');

});

The next method to discuss is the fs.open() method. This method takes a "flag" as the
second argument. If the flag is "w", the specified file is opened for writing and if the called
file does not exist then an empty file is created. The syntax of the fs.open() method will look
like

fs.open('newfile2.txt', 'w', function (err, file) { if

(err) throw err;

console.log('Done!');

});

If you want to replace a particular file and its contents then the fs.writeFile() method is
used. lso, if the file doesn’t already exist, a new one will be created.

23 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

fs.writeFile('newfile3.txt', 'Hello Konfinity!', function (err) { if

(err) throw err;

console.log('Saved!');

});

Apart from these methods included in the file system module of Nodejs, there are a couple
of other methods included too. Let’s look at some of them and understand the concept in
detail.

5.5.3 Update Files (appendFile(), writeFile())

The methods generally used to update files in a system are fs.appendFile() and fs.writeFile().

fs.appendFile() is a method that appends particular content at the end of the file mentioned
in the code. The syntax for the method fs.appendFile() would look like -

fs.appendFile('newfile1.txt', ' This is my text.', function (err) { if

(err) throw err;

console.log('Updated!');

});

This code would append the text "This is my text." to the end of the file that goes by the
name "newfile1.txt".

Another method is the fs.writeFile() one which replaces the file and content mentioned in
the code. The syntax of the method is:

fs.writeFile('mynewfile3.txt', 'This is my text', function (err) { if

(err) throw err;

console.log('Replaced!');

});

The code above replaces the content of the file "newfile3.txt": There are methods to delete
files too.

5.5.4 Delete Files (unlink())

The fs.unlink() method is used to delete a particular file with the File System module. The
syntax of this method will look like -

24 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana
UNIT – 5 [NODE.JS]

fs.unlink('newfile2.txt', function (err) { if

(err) throw err;

console.log ('File deleted!');

});

The code basically deletes the file "newfile2.txt":

5.5.5 Rename Files (rename())

In Nodejs, developers can also upload files to their computer. Apart from this, the file
system module can also be used to rename files. The fs.rename() method is used to rename
a file. This method renames the file mentioned in the code, the syntax for the same will look
like -

fs.rename('vbp.txt', vbp1.txt', function (err) { if

(err) throw err;

console.log('File Renamed!');

});

The code above, renames the file "vbp.txt" to "vbp1.txt":

Also keep in mind that all the methods mentioned above is prefixed with a variable fs. In
these examples above, we took the variable to be ‘fs’, while executing your code, you would
have to explicitly mention it in your code. The code will look something like - var fs =
require('fs');

25 Prepared By:
SUCHIKA PATEL - SDJ International College, Palsana

You might also like