Sunteți pe pagina 1din 68

ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 1

SRI SAIKRUPA DEGREE COLLEGE


(Affiliated to SKU)
LP Circle, Dharmavaram-515671.
-----------------------------------------------------------------

Computer Science Dept.


Cluster - 2
Advanced JavaScript Notes

3rd B.Sc Computer Science

Y Lakshmi Narayana
M.C.A
Lec in Computer & Applications
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 2

III B.Sc– VI Semester –Computer Science-Cluster -2


Advance JavaScript - UNIT – I
Q) What is JQuery and Explain its Features
Ans: JQuery is a small, light-weight and fast JavaScript library. It is cross-platform and
supports different types of browsers. It is also referred as “write less do more”, because it
takes a lot of common tasks that requires many lines of JavaScript code to accomplish, and
binds them into methods that can be called with a single line of code whenever needed. It is
also very useful to simplify a lot of the complicated things from JavaScript, like AJAX
(Asynchronous JavaScript and XML) calls and DOM (Document Object Model)
manipulation.
 jQuery is a small, fast and lightweight JavaScript library.
 jQuery is platform-independent.
 jQuery means "write less do more".
 jQuery simplifies AJAX call and DOM manipulation.
jQuery Features
Following are the important features of jQuery.
 It is very fast and extensible.
 It facilitates the users to write UI related function codes in minimum possible lines.
 It improves the performance of an application.
 Browser's compatible web applications can be developed.
 It uses mostly new features of new browsers.
So, we can say that out of the lot of JavaScript frameworks, jQuery is the most popular and
the most extendable. Many of the biggest companies on the web use jQuery. Some of these
companies are:
1. Microsoft
2. Google
3. IBM
4. Netflix

Q) Explain JQuery Basics (or) What is String, Numbers and Objects in JQuery (or)
Explain Datatypes in JQuery
Ans: jQuery is a framework built using JavaScript capabilities. So, you can use all the
functions and other capabilities available in JavaScript.
String
A string in JavaScript is an immutable object that contains none, one or many characters.
Following are the valid examples of a JavaScript String:

Numbers
Numbers in JavaScript are double-precision 64-bit format IEEE 754 values. They are
immutable, just as strings. Following are the valid examples of a JavaScript Numbers:
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 3

Boolean
A boolean in JavaScript can be either true or false. If a number is zero, it defaults to false. If
there is an empty string, it defaults to false.Following are the valid examples of a JavaScript
Boolean:

Objects
JavaScript supports Object concept very well. You can create an object using the object
literal as follows:

You can write and read properties of an object using the dot notation as follows:

Q) Explain Arrays in JQuery


Ans: Arrays
We can define arrays using the array literal as follows:
var x = [];
var y = [1, 2, 3, 4, 5];
An array has a length property that is useful for iteration:
var x = [1, 2, 3, 4, 5];
for (var i = 0; i < x.length; i++)
{
// Do something with x[i]
}

Q) Explain Functions in JQuery


Ans: Functions A function in JavaScript can be either named or anonymous. A named
function can be defined using function keyword as follows:
function named(){
// do some stuff here
}
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 4

An anonymous function can be defined in similar way as a normal function but it would not
have any name. An anonymous function can be assigned to a variable or passed to a method
as shown below.
var handler = function ()
{
// do some stuff here
}
JQuery makes a use of anonymous functions very frequently as follows:
$(document).ready(function(){
// do some stuff here
});
Arguments
JavaScript variable arguments is a kind of array which has length property. Following
example shows it very well:
function func(x){
console.log(typeof x, arguments.length);
}
func(); //==> "undefined", 0
func(1); //==> "number", 1
func("1", "2", "3"); //==> "string", 3
The arguments object also has a callee property, which refers to the function you're inside.
For example:
function func() {
return arguments.callee;
}
func(); // ==> func
Context
JavaScript famous keyword this always refers to the current context. Within a function thiscontext can
change, depending on how the function is called:
$(document).ready(function() {
// this refers to window.document
});
$("div").click(function() {
// this refers to a div DOM element
});

$("div").click(function() {
// this refers to a div DOM element
});
You can specify the context for a function call using the function-built-in methods call()
and apply() methods. The difference between them is how they pass arguments. Call
passes all arguments through as arguments to the function, while apply accepts an array
as the arguments.
function scope() {
console.log(this, arguments.length);
}
scope() // window, 0
scope.call("foobar", [1,2]); //==> "foobar", 1
scope.apply("foobar", [1,2]); //==> "foobar", 2
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 5

Q) Explain Scope of Variables in JQuery


Ans: Scope: The scope of a variable is the region of your program in which it is defined.
JavaScript variable will have only two scopes.
1. Global Variables: A global variable has global scope which means it is defined everywhere
in your JavaScript code.
2. Local Variables: A local variable will be visible only within a function where it is defined.
Function parameters are always local to that function. Within the body of a function, a local
variable takes precedence over a global variable with the same name:
var myVar = "global"; // ==> Declare a global variable
function ( ) {
var myVar = "local"; // ==> Declare a local variable
document.write(myVar); // ==> local
}

Q) Explain Built in Functions in JQuery


Ans: Built-in Functions JavaScript comes along with a useful set of built-in functions.
These methods can be used to manipulate Strings, Numbers and Dates. Following are the
important JavaScript functions:
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 6

Q) What is CSS? Explain JQuery Selectors


Ans:
 CSS stands for Cascading Style Sheets
 CSS describes how HTML elements are to be displayed on screen, paper, or in other
media
 CSS saves a lot of work. It can control the layout of multiple web pages all at once
 External stylesheets are stored in CSS files
The jQuery library harnesses the power of Cascading Style Sheets (CSS) selectors to let us quickly
and easily access elements or groups of elements in the Document Object Model (DOM). A jQuery
Selector is a function which makes use of expressions to find out matching
elements from a DOM based on the given criteria.
The $() Factory Function
All type of selectors available in jQuery, always start with the dollar sign and parentheses:$(). The
factory function $() makes use of the following three building blocks while selecting elements in a
given document:
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 7

All the above items can be used either on their own or in combination with other selectors.
All the jQuery selectors are based on the same principle except some tweaking.
Example
Following is a simple example which makes use of Tag Selector. This would select all the
elements with a tag name p.
<html>
<head>
<title>the title</title>
<script type="text/javascript" src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var pars = $("p");
for( i=0; i<pars.length; i++ ){
alert("Found paragraph: " + pars[i].innerHTML);
}
});
</script>
</head>
<body>
<div>
<p class="myclass">This is a paragraph.</p>
<p id="myid">This is second paragraph.</p>
<p>This is third paragraph.</p>
</div>
</body>
</html>
This will produce the following result:
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 8

Q) How to Use Selectors?


The selectors are very useful and would be required at every step while using jQuery. They
get the exact element that you want from your HTML document.
Following table lists down few basic selectors and explains them with examples.

jQuery - Element Name Selector: The element selector selects all the elements that have a
tag name of T.
Syntax
Here is the simple syntax to use this selector −
$('tagname')
Parameters
Here is the description of all the parameters used by this selector −
 tagname − Any standard HTML tag name like div, p, em, img, li etc.
Returns
Like any other jQuery selector, this selector also returns an array filled with the found
elements.
Example
 $('p') − Selects all elements with a tag name of p in the document.
 $('div') − Selects all elements with a tag name of div in the document.
Following example would select all the divisions and will apply yellow color to their
background.
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 9

/* This would select all the divisions */


$("div").css("background-color", "yellow");
});
</script>
</head>
<body>
<div class="big" id="div1">
<p>This is first division of the DOM.</p>
</div>
<div class="medium" id="div2">
<p>This is second division of the DOM.</p>
</div>
<div class="small" id="div3">
<p>This is third division of the DOM</p>
</div>
</body>
</html>
This will produce the following result:
This is first division of the DOM.
This is second division of the DOM.
This is third division of the DOM
jQuery - Element ID Selector: The element ID selector selects a single element with the
given id attribute.
Syntax
Here is the simple syntax to use this selector −
$('#elementid')
Parameters
Here is the description of all the parameters used by this selector −
 Elementid: This would be an element ID. If the id contains any special characters like
periods or colons you have to escape those characters with backslashes.
Returns
Like any other jQuery selector, this selector also returns an array filled with the found
element.
Example
 $('#myid') − Selects a single element with the given id myid.
 $('div#yourid') − Selects a single division with the given id yourid.
Following example would select second division and will apply yellow color to its
background as below:
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
/* This would select second division only*/
$("#div2").css("background-color", "yellow");
});
</script>
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 10

</head>
<body>
<div class="big" id="div1">
<p>This is first division of the DOM.</p>
</div>
<div class="medium" id="div2">
<p>This is second division of the DOM.</p>
</div>
<div class="small" id="div3">
<p>This is third division of the DOM</p>
</div>
</body>
</html>
This will produce the following result:
This is first division of the DOM.
This is second division of the DOM.
This is third division of the DOM
jQuery - Element Class Selector
The element class selector selects all the elements which match with the given class of the
elements.
Syntax
Here is the simple syntax to use this selector:
$('.classid')
Parameters
Here is the description of all the parameters used by this selector −
 classid − This is class ID available in the document.
Returns
Like any other jQuery selector, this selector also returns an array filled with the found
elements.
Example
 $('.big') − Selects all the elements with the given class ID big.
 $('p.small') − Selects all the paragraphs with the given class ID small.
 $('.big.small') − Selects all the elements with a class of big and small.
Following example would select all divisions with class .big and will apply yellow color to its
background
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
/* This would select second division only*/
$(".big").css("background-color", "yellow");
});
</script>
</head>
<body>
<div class="big" id="div1">
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 11

<p>This is first division of the DOM.</p>


</div>
<div class="medium" id="div2">
<p>This is second division of the DOM.</p>
</div>
<div class="small" id="div3">
<p>This is third division of the DOM</p>
</div>
</body>
</html>
This will produce the following result:
This is first division of the DOM.
This is second division of the DOM.
This is third division of the DOM
jQuery - Universal Selector: The universal selector selects all the elements available in the
document.
Syntax
Here is the simple syntax to use this selector −
$('*')
Parameters
Here is the description of all the parameters used by this selector –
* − A symbolic star.
Returns
Like any other jQuery selector, this selector also returns an array filled with the found
elements.
Example
 $('*') selects all the elements available in the document.
Following example would select all the elements and will apply yellow color to their
background. Try to understand that this selector will select every element including head,
body etc.

<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
/* This would select all the elements */
$("*").css("background-color", "yellow");
});
</script>
</head>
<body>
<div class="big" id="div1">
<p>This is first division of the DOM.</p>
</div>
<div class="medium" id="div2">
<p>This is second division of the DOM.</p>
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 12

</div>
<div class="small" id="div3">
<p>This is third division of the DOM</p>
</div>
</body>
</html>
This will produce the following result:
This is first division of the DOM.
This is second division of the DOM.
This is third division of the DOM
jQuery - Multiple Elements Selector: This Multiple Elements selector selects the combined
results of all the specified selectors E, F or G.
You can specify any number of selectors to combine into a single result. Here order of the
DOM elements in the jQuery object aren't necessarily identical.
Syntax
Here is the simple syntax to use this selector –
$('E, F, G,....')
Parameters
Here is the description of all the parameters used by this selector −
 E − Any valid selector
 F − Any valid selector
 G − Any valid selector
Returns
Like any other jQuery selector, this selector also returns an array filled with the found
elements.

Example
 $('div, p') − selects all the elements matched by div or p.
 $('p strong, .myclass') − selects all elements matched by strong that are descendants of
an element matched by p as well as all elements that have a class of myclass.
 $('p strong, #myid') − selects a single elements matched by strong that is descendant
of an element matched by p as well as element whose id is myid. Following example
would select elements with class ID big and element with ID div3 and will apply
yellow color to its background −
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(".big, #div3").css("background-color", "yellow");
});
</script>
</head>
<body>
<div class="big" id="div1">
<p>This is first division of the DOM.</p>
</div>
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 13

<div class="medium" id="div2">


<p>This is second division of the DOM.</p>
</div>
<div class="small" id="div3">
<p>This is third division of the DOM</p>
</div>
</body>
</html>
This will produce the following result:
This is first division of the DOM.
This is second division of the DOM.
This is third division of the DOM

Q) Explain about Callback Function in JQuery


Ans: jQuery Callback Functions
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);
Examples
The example below has a callback parameter that is a function that will be executed after the
hide effect is completed:
Example with Callback
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
The example below has no callback parameter, and the alert box will be displayed before the
hide effect is completed:
Example without Callback
$("button").click(function(){
$("p").hide(1000);
alert("The paragraph is now hidden");
});

Q) Explain about GET and SET Attributes (or) Explain about JQuery Attributes
Ans: Some of the most basic components we can manipulate when it comes to DOM
elements are the properties and attributes assigned to those elements. Most of these attributes
are available through JavaScript as DOM node properties. Some of the more common
properties are:
 className
 tagName
 id
 href
 title
 rel
 Src
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 14

Consider the following HTML markup for an image element:


<img id="myImage" src="image.gif" alt="An image"
class="someClass" title="This is an image"/>
In this element's markup, the tag name is img, and the markup for id, src, alt, class, and title
represents the element's attributes, each of which consists of a name and a value. jQuery
gives us the means to easily manipulate an element's attributes and gives us access to the
element so that we can also change its properties.
1.Get Attribute Value
The attr() method can be used to either fetch the value of an attribute from the first element
in the matched set or set attribute values onto all matched elements.
Example
Following is a simple example which fetches title attribute of <em> tag and set <div
id="divid"> value with the same value:
<html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var title = $("em").attr("title");
$("#divid").text(title);
});
</script>
</head>
<body>
<div>
<em title="Bold and Brave">This is first paragraph.</em>
<p id="myid">This is second paragraph.</p>
<div id="divid"></div>
</div>
</body>
</html>
This will produce the following result:
This is first paragraph.
This is second paragraph.
Bold and Brave
2.Set Attribute Value
The attr(name, value) method can be used to set the named attribute onto all elements
in the wrapped set using the passed value.
Example
Following is a simple example which set src attribute of an image tag to a correct location:
<html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#myimg").attr("src", "/images/jquery.jpg");
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 15

});
</script>
</head>
<body>
<div>
<img id="myimg" src="/wongpath.jpg" alt="Sample image" />
</div>
</body>
</html>

This will produce the following result:

Applying Styles
The addClass( classes ) method can be used to apply defined style sheets onto all the
matched elements. You can specify multiple classes separated by space.
Example
Following is a simple example which sets class attribute of a para <p> tag:
<html>
<head>
<title>the title</title>
<script type="text/javascript" src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("em").addClass("selected");
$("#myid").addClass("highlight");
});
</script>
<style>
.selected { color:red; }
.highlight { background:yellow; }
</style>
</head>
<body>
<em title="Bold and Brave">This is first paragraph.</em>
<p id="myid">This is second paragraph.</p>
</body>
</html>
This will produce the following result:
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 16

Attribute Methods
Following table lists down few useful methods which you can use to manipulate attributes
and properties:
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 17

Q) What is JQuery Traversing and Explain about DOM Traversing Methods


Ans: jQuery traversing, which means "move through", are used to "find" (or select) HTML
elements based on their relation to other elements. Start with one selection and move through
that selection until you reach the elements you desire. The image below illustrates an HTML
page as a tree (DOM tree). With jQuery traversing, you can easily move up (ancestors), down
(descendants) and sideways (siblings) in the tree, starting from the selected (current) element.
This movement is called traversing - or moving through - the DOM tree.
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 18

 The <div> element is the parent of <ul>, and an ancestor of everything inside of it
 The <ul> element is the parent of both <li> elements, and a child of <div>
 The left <li> element is the parent of <span>, child of <ul> and a descendant of
<div>
 The <span> element is a child of the left <li> and a descendant of <ul> and <div>
 The two <li> elements are siblings (they share the same parent)
 The right <li> element is the parent of <b>, child of <ul> and a descendant of
<div>
 The <b> element is a child of the right <li> and a descendant of <ul> and <div>
jQuery is a very powerful tool which provides a variety of DOM traversal methods to help
us select elements in a document randomly as well as in sequential method. Most of the
DOM Traversal Methods do not modify the jQuery object and they are used to filter out
elements from a document based on given conditions.
Find Elements by Index
Consider a simple document with the following HTML content:
<html>
<head>
<title>the title</title>
</head>
<body>
<div>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
</div>
</body>
</html>
This will produce the following result:
 list item 1
 list item 2
 list item 3
 list item 4
 list item 5
 list item 6
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 19

Above every list has its own index, and can be located directly by using eq(index) method as
below example.
 Every child element starts its index from zero, thus, list item 2 would be accessed
by using $("li").eq(1) and so on.
Example
Following is a simple example which adds the color to second list item.
<html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("li").eq(2).addClass("selected");
});
</script>
<style>
.selected { color:red; }
</style>
</head>
<body>
<div>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
</div>
</body>
</html>
This will produce the following result:
 list item 1
 list item 2
 list item 3
 list item 4
 list item 5
 list item 6
Locating Descendent Elements
The find( selector ) method can be used to locate all the descendent elements of a
particular type of elements. The selector can be written using any selector syntax.
Example
Following is an example which selects all the <span> elements available inside different
<p> elements:
<html>
<head>
<title>the title</title>
<script type="text/javascript" src="/jquery/jquery-1.3.2.min.js"></script>
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 20

<script type="text/javascript" language="javascript">


$(document).ready(function() {
$("p").find("span").addClass("selected");
});
</script>
<style>
.selected { color:red; }
</style>
</head>
<body>
<p>This is 1st paragraph and <span>THIS IS RED</span></p>
<p>This is 2nd paragraph and <span>THIS IS ALSO RED</span></p>
</body>
</html>
This will produce the following result
This is 1st paragraph and THIS IS RED
This is 2nd paragraph and THIS IS ALSO RED

Q) Explain about DOM Filtering Methods


Ans: JQuery DOM Filter Methods
Following table lists down useful methods which you can use to filter out various elements
from a list of DOM elements:
The first(), last(), eq(), filter() and not() Methods
The most basic filtering methods are first(), last() and eq(), which allow you to select a
specific element based on its position in a group of elements. Other filtering methods, like
filter() and not() allow you to select elements that match, or do not match, a certain criteria.
jQuery first() Method
The first() method returns the first element of the specified elements.
The following example selects the first <div> element:
Example
$(document).ready(function(){
$("div").first();
});
jQuery last() Method
The last() method returns the last element of the specified elements.
The following example selects the last <div> element:

Example
$(document).ready(function(){
$("div").last();
});
jQuery eq() method
The eq() method returns an element with a specific index number of the selected elements.
The index numbers start at 0, so the first element will have the index number 0 and not 1. The
following example selects the second <p> element (index number 1):
Example
$(document).ready(function(){
$("p").eq(1);
});
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 21

jQuery filter() Method


The filter() method lets you specify a criteria. Elements that do not match the criteria are
removed from the selection, and those that match will be returned. The following example
returns all <p> elements with class name "intro":
Example
$(document).ready(function(){
$("p").filter(".intro");
});
jQuery not() Method
The not() method returns all elements that do not match the criteria.
Tip: The not() method is the opposite of filter().
The following example returns all <p> elements that do not have class name "intro":
Example
$(document).ready(function(){
$("p").not(".intro");
});

Q) Explain about jQuery Traversing - Descendants


Ans: jQuery Traversing - Descendants
A descendant is a child, grandchild, great-grandchild, and so on.
With jQuery you can traverse down the DOM tree to find descendants of an element.
Traversing Down the DOM Tree
Two useful jQuery methods for traversing down the DOM tree are:
children()
find()
jQuery children() Method
The children() method returns all direct children of the selected element.
This method only traverse a single level down the DOM tree.
The following example returns all elements that are direct children of each <div> elements:
Example
$(document).ready(function(){
$("div").children();
});
You can also use an optional parameter to filter the search for children.
The following example returns all <p> elements with the class name "first", that are direct
children of <div>:
Example
$(document).ready(function(){
$("div").children("p.first");
});
jQuery find() Method
The find() method returns descendant elements of the selected element, all the way down to
the last descendant. The following example returns all <span> elements that are descendants
of <div>:
Example
$(document).ready(function(){
$("div").find("span");
});
The following example returns all descendants of <div>:
Example
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 22

$(document).ready(function(){
$("div").find("*");
});

III B.Sc– VI Semester –Computer Science-Cluster -2


Advance JavaScript - UNIT – II
Q) Explain about CSS Methods (or) How to Apply CSS Properties
Ans: Using JQuery library developers can enhance their websites without worrying about
browsers and their versions as long as the browsers have JavaScript enabled. Most of the
JQuery CSS Methods do not modify the content of the jQuery object and they are used to
apply CSS properties on DOM elements Apply Multiple CSS Properties You can apply
multiple CSS properties using a single JQuery method CSS( {key1:val1,key2:val2....). You
can apply as many properties as you like in a single call.
Here is the syntax for the method:
selector.css( {key1:val1, key2:val2....keyN:valN});
Example:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 23

$("li").eq(2).css({"color":"red",
"background-color":"green"});
});

Setting Element Width & Height The width( val ) and height( val ) method can be used to set
the width and height respectively of any element.
Ex: $("div:first").width(100);
JQuery CSS Methods Following table lists down all the methods which you can use to play
with CSS properties
Sr.No. Method & Description
1 css( name )
Return a style property on the first matched element.
2 css( name, value )
Set a single style property to a value on all matched elements.
3 css( properties )
Set a key/value object as style properties to all matched elements.
4 height( val )
Set the CSS height of every matched element.
5 height( )
Get the current computed, pixel, height of the first matched element.
6 innerHeight( )
Gets the inner height (excludes the border and includes the padding) for the first matched
element.
7 innerWidth( )
Gets the inner width (excludes the border and includes the padding) for the first matched
element.
Q) Explain DOM Manipulation Methods
Ans: Query provides methods to manipulate DOM in efficient way. You do not need to write
big code to modify the value of any element's attribute or to extract HTML code from a
paragraph or division. JQuery provides methods such as .attr(), .html(), and .val() which act
as getters, retrieving information from DOM elements. Content Manipulation The html( )
method gets the html contents (innerHTML) of the first matched element. Here is the
syntax for the method
selector.html( )
DOM Element Replacement We can replace a complete DOM element with the specified
HTML or DOM elements. The replaceWith( content ) method serves this purpose very well.
Here is the syntax for the method −
selector.replaceWith( content )
Here content is what you want to have instead of original element. This could be HTML or
simple text.
Removing DOM Elements JQuery provides two methods to handle the situation. The empty(
) method remove all child nodes from the set of matched elements where as the method
remove( expr ) method removes all matched elements from the DOM. Here is the syntax for
the method −
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 24

selector.remove( [ expr ])
or
selector.empty( )
We can pass optional parameter expr to filter the set of elements to be removed. Inserting
DOM Elements JQuery provides various methods to insert elements at various
locations. The after( content ) method insert content after each of the matched elements
where as the method before( content ) method inserts content before each of the matched
elements. Here is the syntax for the method −
selector.after( content )
or
selector.before( content )
Example Following is an example where <div> elements are being inserted just before the
clicked element:
1. <html>
2. <head>
3. <title>the title</title>
4. <script type="text/javascript"
5. src="/jquery/jquery-1.3.2.min.js"></script>
6. <script type="text/javascript" language="javascript">
7. $(document).ready(function() {
8. $("div").click(function () {
9. $(this).before('<div class="div"></div>' );
10. });
11. });
12. </script>
13. <style>
14. .div{ margin:10px;padding:12px;
15. border:2px solid #666;
16. width:60px;
17. }
18. </style>
19. </head>
20. <body>
21. <p>Click on any square below:</p>
22. <span id="result"> </span>
23. <div class="div" style="background-color:blue;"></div>
24. <div class="div" style="background-color:green;"></div>
25. <div class="div" style="background-color:red;"></div>
26. </body>
27. </html>
This will produce the following result: Click on any square below:

DOM Manipulation Methods Following table lists down all the methods which you can use
to manipulate DOM elements − Sr.No. Method & Description
1 after( content )
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 25

Insert content after each of the matched elements.


2 append( content )
Append content to the inside of every matched element.
3 appendTo( selector )
Append all of the matched elements to another, specified, set of elements.
4 before( content )
Insert content before each of the matched elements.
5 clone( bool )
Clone matched DOM Elements, and all their event handlers, and select the clones.
6 clone( )
Clone matched DOM Elements and select the clones.
7 empty( )
Remove all child nodes from the set of matched elements.
8 html( val )
Set the html contents of every matched element.

Q) Explain JQuery Event Handling


Ans: We have the ability to create dynamic web pages by using events. Events are actions
that can be detected by your Web Application.
Following are the examples events −
A mouse click
A web page loading
Taking mouse over an element
Submitting an HTML form
A keystroke on your keyboard, etc.
When these events are triggered, you can then use a custom function to do pretty much
whatever you want with the event. These custom functions call Event Handlers. Binding
Event Handlers Using the jQuery Event Model, we can establish event handlers on DOM
elements with the bind() method as follows. The full syntax of the bind() command is as
follows −
selector.bind( eventType[, eventData], handler)
Following is the description of the parameters –
eventType − A string containing a JavaScript event type, such as click or submit. Refer to
the next section for a complete list of event types.
eventData − This is optional parameter is a map of data that will be passed to the event
handler.
handler − A function to execute each time the event is triggered.
Removing Event Handlers Once an event handler is established, it remains in effect for the
remainder of the life of the page. There may be a need when you would like to remove event
handler. jQuery provides the unbind() command to remove an exiting event handler. The
syntax of unbind() is as follows −
selector.unbind(eventType, handler)
or
selector.unbind(eventType)
Following is the description of the parameters −
eventType − A string containing a JavaScript event type, such as click or submit. Refer to the
next section for a complete list of event types. handler − If provided, identifies the specific
listener that's to be removed.
Event Types The following are cross platform and recommended event types which you can
bind
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 26

using JQuery −
The Event Object and The Event Attributes
The event object is often unnecessary and the parameter is omitted, as sufficient context is
usually available when the handler is bound to know exactly what needs to be done when the
handler is triggered, however there are certain attributes which you would need to be
accessed.

Q) Explain about JQuery Effects Methods


Ans: jQuery provides a trivially simple interface for doing various kind of amazing effects.
JQuery methods allow us to quickly apply commonly used effects with a minimum
configuration. This tutorial covers all the important jQuery methods to create visual effects.
Showing and Hiding Elements
The commands for showing and hiding elements are pretty much what we would expect
− show() to show the elements in a wrapped set and hide() to hide them.
Syntax Here is the simple syntax for show() method −
[selector].show( speed, [callback] );
Here is the description of all the parameters −
speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast")
or the number of milliseconds to run the animation (e.g. 1000).
callback − This optional parameter represents a function to be executed whenever the
animation completes; executes once for each element animated against.
Following is the simple syntax for hide() method –
[selector].hide( speed, [callback] );
Toggling the Elements jQuery provides methods to toggle the display state of elements
between revealed or hidden. If the element is initially displayed, it will be hidden; if hidden,
it will be shown.
Syntax
Here is the simple syntax for one of the toggle() methods −
[selector]..toggle([speed][, callback]);
JQuery Effect Methods We have seen basic concept of jQuery Effects. Following table lists
down all the important methods to create different kind of effects −
Sr.No. Methods & Description
1 animate( params, [duration, easing, callback] )
A function for making custom animations.
2 fadeIn( speed, [callback] )
Fade in all matched elements by adjusting their opacity and firing an optional callback after
completion.
3 fadeOut( speed, [callback] )
Fade out all matched elements by adjusting their opacity to 0, then setting display to "none"
and firing an optional callback after completion.
4 fadeTo( speed, opacity, callback )
Fade the opacity of all matched elements to a specified opacity and firing an optional
callback after completion.
5 hide( )
Hides each of the set of matched elements if they are shown.
6 hide( speed, [callback] )
Hide all matched elements using a graceful animation and firing an optional callback after
completion.
7 show( ) Displays each of the set of matched elements if they are hidden.
8 show( speed, [callback] )
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 27

Show all matched elements using a graceful animation and firing an optional callback after
completion.

Q) Explain about JQuery Sliding Methods


Ans: With jQuery you can create a sliding effect on elements. jQuery has the following slide
methods:
slideDown()
slideUp()
slideToggle()
jQuery slideDown() Method 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. The following example demonstrates the slideDown()
method:
Example
$("#flip").click(function(){
$("#panel").slideDown();
});
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. The following example demonstrates the slideUp()
method:
Example
$("#flip").click(function(){
$("#panel").slideUp();
});
jQuery slideToggle() Method 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.
$(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.
The following example demonstrates the slideToggle() method:
Example
$("#flip").click(function(){
$("#panel").slideToggle();
});

Q) Explain about JQuery Fading Methods


Ans: With jQuery you can fade an element in and out of visibility. jQuery has the following
fade methods:
fadeIn()
fadeOut()
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 28

fadeToggle()
fadeTo()
jQuery fadeIn() Method The jQuery fadeIn() method is used to fade in a hidden element.
Syntax:
$(selector).fadeIn(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 fading completes. The following example demonstrates the fadeIn()
method with different parameters:
Example
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
jQuery fadeOut() Method The jQuery fadeOut() method is used to fade out a visible
element.
Syntax:
$(selector).fadeOut(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 fading completes. The following example demonstrates the fadeOut()
method with different parameters:
Example
$("button").click(function(){
$("#div1").fadeOut();
$("#div2").fadeOut("slow");
$("#div3").fadeOut(3000);
});
Query fadeToggle() Method The jQuery fadeToggle() method toggles between the fadeIn()
and
fadeOut() methods.
If the elements are faded out, fadeToggle() will fade them in.
If the elements are faded in, fadeToggle() will fade them out.
Syntax:
$(selector).fadeToggle(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 fading completes.
The following example demonstrates the fadeToggle() method with different parameters:
Example
$("button").click(function(){
$("#div1").fadeToggle();
$("#div2").fadeToggle("slow");
$("#div3").fadeToggle(3000);
});
jQuery fadeTo() Method The jQuery fadeTo() method allows fading to a given opacity
(value
between 0 and 1).
Syntax:
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 29

$(selector).fadeTo(speed,opacity,callback);
The required speed parameter specifies the duration of the effect. It can take the following
values: "slow", "fast", or milliseconds. The required opacity parameter in the fadeTo()
method specifies fading to a given opacity (value between 0 and 1).
The optional callback parameter is a function to be executed after the function completes.
The following example demonstrates the fadeTo() method with different parameters:
Example
$("button").click(function(){
$("#div1").fadeTo("slow", 0.15);
$("#div2").fadeTo("slow", 0.4);
$("#div3").fadeTo("slow", 0.7);
});

Q) Explain about JQuery Custom Animation (or) Explain about Animations in JQuery
Ans: The animate() method performs a custom animation of a set of CSS properties. This
method changes an element from one state to another with CSS styles. The CSS property
value is changed gradually, to create an animated effect. Only numeric values can be
animated (like "margin:30px"). String values cannot be animated (like "background-
color:red"), except for the strings "show", "hide" and "toggle". These values allow hiding and
showing the animated element.
Syntax
(selector).animate({styles},speed,easing,callback)
jQuery animate() - Using Relative Values It is also possible to define relative values (the
value is then relative to the element's current value). This is done by putting += or -= in front
of the value: Example
$("button").click(function(){
$("div").animate({
left: '250px',
height: '+=150px',
width: '+=150px'
});
});
Parameter Description
styles Only numeric values can be animated (like "margin:30px"). String values cannot be
animated (like "background-color:red"), except for the strings "show", "hide" and "toggle".
These values allow hiding and showing the animated element. speed Optional. Specifies the
speed of the animation. Default value is 400 milliseconds Possible values: milliseconds (like
100, 1000, 5000, etc)
"slow"
"fast"
easing Optional. Specifies the speed of the element in different points of the animation.
Default value is "swing". Possible values:
"swing" - moves slower at the beginning/end, but faster in the middle
"linear" - moves in a constant speed
Tip: More easing functions are available in external plugins.
callback Optional. A function to be executed after the animation completes.
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 30

III B.Sc– VI Semester –Computer Science-Cluster -2


Advance JavaScript - UNIT – III
Q) What is JQuery UI? Explain its Features
Ans: JqueryUI is a powerful Javascript library built on top of jQuery JavaScript
library. UI stands
for User interface, It is a set of plug-ins for jQuery that adds new functionalities to the
jQuery core library. The set of plug-ins in JqueryUI includes interface interactions, effects,
animations,widgets, and themes built on top of jQuery JavaScript Library. It was released in
September 2007, announced in a blog post by John Resig on jquery.com Features JqueryUI
is categorized into four groups namely, Interactions, Widgets, Effects, and Utilities. These
will be discussed in detail in the subsequent chapters. The structure of the library is as shown
in the image below:

Interactions − These are the interactive plugins like drag, drop, resize and more which give
the user the ability to interact with DOM elements. Widgets − Using widgets which are
jQuery plugins, you can create user interface elements like accordian,datepicker etc. Effects
− These are built on the internal jQuery effects. They contain a full suite of custom
animations and transitions for DOM elements.
Utilities − These are a set of modular tools the JqueryUI library uses internally.
Benefits of JqueryUI
The below are some of the benefits of Jquery UI −
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 31

Cohesive and Consistent APIs.


Comprehensive Browser Support.
Open Source and Free to Use.
Good Documentation.
Powerful Theming Mechanism.
Stable and Maintenance Friendly.
Q) How to Download JQuery UI (or) How to set Environment of JQuery UI
Ans: JqueryUI library can be used in two ways in your web page −
1.Downloading UI Library from its official website
2.Downloading UI Library from CDNs
1.Download UI Library from Its Official Website When you open the link
http://jqueryui.com/,
you will see there are three options to download JqueryUI library –

Custom Download − Click on this button to download a customized version of library.


Stable − Click on this button to get the stable and latest version of JqueryUI library.
Legacy − Click on this button to get the previous major release of the JqueryUI library.
The directory structure of this version is shown in the following figure –

2.Download UI Library from CDNs A CDN or Content Delivery Network is a network of


servers designed to serve files to users. If you use a CDN link in your web page, it moves the
responsibility of hosting files from your own servers to a series of external ones. This also
offers an advantage that if the visitor to your webpage has already downloaded a copy of
JqueryUI from the same CDN, it won't have to be re-downloaded. The jQuery Foundation,
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 32

Google, and Microsoft all provide CDNs that host jQuery core as well as jQuery UI. Because
a CDN does not require you to host your own version of jQuery and jQuery UI, it is perfect
for demos and experimentation.
Example Now let us write a simple example using JqueryUI. Let us create an HTML file,
copy the following content to the <head> tag −
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
Details of the above code are −
The first line, adds jQuery UI theme (in our case ui-lightness) via CSS. This CSS will
make
our UI stylish.
Second line, adds the jQuery library, as jQuery UI is built on top of jQuery library.
Third line, adds the jQuery UI library. This enables jQuery UI in your page.

Q) Explain about JQuery UI Draggable


jQueryUI provides draggable() method to make any DOM element draggable. Once the
element is draggable, you can move that element by clicking on it with the mouse and
dragging it anywhere within the viewport. Syntax The draggable() method can be used in
two forms − $(selector, context).draggable (options) Method
$(selector, context).draggable ("action", [params]) Method
$ (selector, context).draggable (options) Method
The draggable (options) method declares that an HTML element can be moved in the HTML
page.
The options parameter is an object that specifies the behavior of the elements involved.
Syntax
$(selector, context).draggable(options);
You can provide one or more options at a time using Javascript object. If there are more than
one options to be provided then you will separate them using a comma as follows −
$(selector, context).draggable({option1: value1, option2: value2..... });
Example: $(function() {
$( "#draggable" ).draggable();
});

Q) Explain about JQuery UI Droppable


Ans: jQueryUI provides droppable() method to make any DOM element droppable at a
specified
target (a target for draggable elements).
Syntax The droppable() method can be used in two forms −
$(selector, context).droppable (options) Method
$(selector, context).droppable ("action", params) Method
$ (selector, context).droppable (options) Method
The droppable (options) method declares that an HTML element can be used as an element
in which you can drop other elements. The options parameter is an object that specifies the
behavior of the elements involved.
Syntax
$(selector, context).droppable (options);
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 33

You can provide one or more options at a time using Javascript object. If there are more than
one options to be provided then you will separate them using a comma as follows −
$(selector, context).droppable({option1: value1, option2: value2..... });

Q) Explain about JQuery UI Resizable


Ans: jQueryUI provides resizable() method to resize any DOM element. This method
simplifies the resizing of element which otherwise takes time and lot of coding in HTML.
The resizable () method displays an icon in the bottom right of the item to resize.
Syntax The resizable() method can be used in two forms −
$(selector, context).resizable (options) Method
$(selector, context).resizable ("action", params) Method
$ (selector, context).resizable (options) Method
The resizable (options) method declares that an HTML element can be resized.
The options parameter is an object that specifies the behavior of the elements involved when
resizing.
Syntax $(selector, context).resizable (options);
You can provide one or more options at a time of using Javascript object. If there are more
than one options to be provided then you will separate them using a comma as follows −
$(selector, context).resizable({option1: value1, option2: value2..... });

Q) Explain about JQuery UI Selectable


Ans: jQueryUI provides selectable() method to select DOM element individually or in a
group. With this method elements can be selected by dragging a box (sometimes called a
lasso) with the mouse over the elements. Also, elements can be selected by clicking or
dragging while holding the Ctrl/Meta key, allowing for multiple (non-contiguous) selections.
Syntax
The selectable() method can be used in two forms −
$(selector, context).selectable (options) Method
$(selector, context).selectable ("action", params) Method
$ (selector, context).selectable (options) Method
The selectable (options) method declares that an HTML element contains selectable items.
The options parameter is an object that specifies the behavior of the elements involved when
selecting.
Syntax $(selector, context).selectable (options);
You can provide one or more options at a time using Javascript object. If there are more than
one options to be provided, then you will separate them using a comma as follows −
$(selector, context).selectable({option1: value1, option2: value2..... });

Q) Explain about JQuery UI Sortable


Ans: jQueryUI provides sortable() method to reorder elements in list or grid using the mouse.
This method performs sortability action based upon an operation string passed as the first
parameter.
Syntax
The sortable () method can be used in two forms −
$(selector, context).sortable (options) Method
$(selector, context).sortable ("action", [params]) Method
$ (selector, context).sortable (options) Method
The sortable (options) method declares that an HTML element contains interchangeable
elements. The options parameter is an object that specifies the behavior of the elements
involved during reordering.
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 34

Syntax
$(selector, context).sortable(options);

Q) Explain about JQuery UI Accordion (or) Explain Widgets in JQuery UI


Ans: Accordion Widget in jQueryUI is a jQuery based expandable and collapsible content
holder that is broken into sections and probably looks like tabs. jQueryUI provides
accordion() method to achieve this.
Syntax
The accordion() method can be used in two forms −
$(selector, context).accordion (options) Method
$(selector, context).accordion ("action", params) Method
$ (selector, context).accordion (options) Method
The accordion (options) method declares that an HTML element and its contents should be
treated and managed as accordion menus. The optionsparameter is an object that specifies the
appearance and behavior of the menu involved.
Syntax
$(selector, context).accordion (options);
You can provide one or more options at a time using Javascript object. If there are more than
one options to be provided then you will separate them using a comma as follows −
$(selector, context).accordion({option1: value1, option2: value2..... });

Q) Explain about JQuery UI Autocomplete


Ans: Auto completion is a mechanism frequently used in modern websites to provide the user
with a list of suggestions for the beginning of the word, which he/she has typed in a text box.
The user can then select an item from the list, which will be displayed in the input field. This
feature prevents the user from having to enter an entire word or a set of words.
JQueryUI provides an autocomplete widget — a control that acts a lot like a <select>
dropdown, but filters the choices to present only those that match what the user is typing into
a control. jQueryUI provides the autocomplete()method to create a list of suggestions below
the input field and adds new CSS classes to the elements concerned to give them the
appropriate style. Any field that can receive input can be converted into an Autocomplete,
namely, <input> elements, <textarea> elements, and elements with the content editable
attribute.
Syntax The autocomplete() method can be used in two forms −
$(selector, context).autocomplete (options) Method
$(selector, context).autocomplete ("action", params) Method
$ (selector, context).autocomplete (options) Method
The autocomplete (options) method declares that an HTML <input> element must be
managed as an input field that will be displayed above a list of suggestions. The options
parameter is an object that specifies the behavior of the list of suggestions when the user is
typing in the input field.
Syntax
$(selector, context).autocomplete (options);
You can provide one or more options at a time using Javascript object. If there are more than
one options to be provided then you will separate them using a comma as follows −
$(selector, context).autocomplete({option1: value1, option2: value2..... });

Q) Explain about JQuery UI Button


Ans: jQueryUI provides button() method to transform the HTML elements (like buttons,
inputs and anchors) into themeable buttons, with automatic management of mouse
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 35

movements on them, all managed transparently by jQuery UI. In order to group radio buttons,
Button also provides an additional widget, called Buttonset. Buttonset is used by selecting a
container element (which contains the radio buttons) and calling .buttonset().
Syntax
The button() method can be used in two forms −
$(selector, context).button (options) Method
$(selector, context).button ("action", params) Method
$ (selector, context).button (options) Method
The button (options) method declares that an HTML element should be treated as button. The
options parameter is an object that specifies the behavior and appearance of the button.
Syntax
$(selector, context).button (options);
You can provide one or more options at a time using Javascript object. If there are more than
one options to be provided then you will separate them using a comma as follows −
$(selector, context).button({option1: value1, option2: value2..... });

Q) Explain about JQuery UI Data Picker


Ans: Datepickers in jQueryUI allow users to enter dates easily and visually. You can
customize the date format and language, restrict the selectable date ranges and add in buttons
and other navigation options easily. jQueryUI provides datepicker() method that creates a
datepicker and changes the appearance of HTML elements on a page by adding new CSS
classes. Transforms the <input>, <div>, and <span> elements in the wrapped set into a
datepicker control.
Syntax
The datepicker() method can be used in two forms −
$(selector, context).datepicker (options) Method
$(selector, context).datepicker ("action", [params]) Method
$ (selector, context).datepicker (options) Method
The datepicker (options) method declares that an <input> element (or <div>, or <span>,
depending on how you choose to display the calendar) should be managed as a datepicker.
The options parameter is an object that specifies the behavior and appearance of the
datepicker elements.
Syntax $(selector, context).datepicker(options);
You can provide one or more options at a time using Javascript object. If there are more than
one options to be provided then you will separate them using a comma as follows −
$(selector, context).datepicker({option1: value1, option2: value2..... });

Q) Explain about JQuery UI Dialog


Ans: Dialog boxes are one of the nice ways of presenting information on an HTML page. A dialog
box is a floating window with a title and content area. This window can be moved, resized, and of
course, closed using "X" icon by default. jQueryUI provides dialog() method that transforms the
HTML code written on the page into HTML code to display a dialog box.
Syntax The dialog() method can be used in two forms −
$(selector, context).dialog (options) Method
$(selector, context).dialog ("action", [params]) Method
$ (selector, context).dialog (options) Method
The dialog (options) method declares that an HTML element can be administered in the form of a
dialog box. The options parameter is an object that specifies the appearance and behavior of that
window.
Syntax
$(selector, context).dialog(options);
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 36

You can provide one or more options at a time using Javascript object. If there are more than one
options to be provided then you will separate them using a comma as follows −
$(selector, context).dialog({option1: value1, option2: value2..... });

Q) Explain about JQuery UI Menu


Ans: A menu widget usually consists of a main menu bar with pop up menus. Items in pop up
menus often have sub pop up menus. A menu can be created using the markup elements as
long as the parent-child relation is maintained (using <ul> or <ol>). Each menu item has an
anchor element. The Menu Widget in jQueryUI can be used for inline and popup menus, or
as a base for building more complex menu systems. For example, you can create nested
menus with custom positioning. jQueryUI provides menu() methods to create a menu.
Syntax
The menu() method can be used in two forms −
$(selector, context).menu (options) Method
$(selector, context).menu ("action", params) Method
$ (selector, context).menu (options) Method
The menu (options) method declares that an HTML element and its contents should be
treated and managed as menus. The options parameter is an object that specifies the
appearance and behavior of the menu items involved.
Syntax
$(selector, context).menu (options);
You can provide one or more options at a time using Javascript object. If there are more than
one options to be provided then you will separate them using a comma as follows −
$(selector, context).menu({option1: value1, option2: value2..... });

Q) Explain about JQuery UI Progress Bar


Ans: Progress bars indicate the completion percentage of an operation or process. We can
categorize progress bar as determinate progress bar and indeterminate progress bar.
Determinate progress bar should only be used in situations where the system can accurately
update the current status. A determinate progress bar should never fill from left to right, then
loop back to empty for a single process. If the actual status cannot be calculated, an
indeterminate progress barshould be used to provide user feedback. jQueryUI provides an
easy-to-use progress bar widget that we can use to let users know that our application is hard
at work performing the requested operation. jQueryUI provides progressbar() method to
create progress bars.
Syntax
The progressbar() method can be used in two forms −
$(selector, context).progressbar (options) Method
$(selector, context).progressbar ("action", params) Method
$ (selector, context).progressbar (options) Method
The progressbar (options) method declares that an HTML element can be managed in the
form of a progress bar. The options parameter is an object that specifies the appearance and
behavior of progress bars.
Syntax $(selector, context).progressbar (options);
You can provide one or more options at a time using Javascript object. If there are more than
one options to be provided then you will separate them using a comma as follows −
$(selector, context).progressbar({option1: value1, option2: value2..... });

Q) Explain about JQuery UI Slider


Ans: A slider is used whenever a numeric value within a certain range is to be obtained. The
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 37

advantage of a slider over text input is that it becomes impossible for the user to enter a bad
value. Any value that they can pick with the slider is valid. jQueryUI provides us a slider
control through slider widget. jQueryUI provides slider() method changes the appearance of
HTML elements in the page, adding new CSS classes that give them the appropriate style.
Syntax
The slider () method can be used in two forms −
$(selector, context).slider (options) Method
$(selector, context).slider ("action", params) Method
$ (selector, context).slider (options) Method
The slider (options) method declares that an HTML element should be managed as a slider.
The options parameter is an object that specifies the appearance and behavior of slider.
Syntax
$(selector, context).slider (options);
You can provide one or more options at a time using Javascript object. If there are more than
one options to be provided then you will separate them using a comma as follows −
$(selector, context).slider({option1: value1, option2: value2..... });

Q) Explain about JQuery UI Spinner


Ans: Spinner widget adds a up/down arrow to the left of a input box thus allowing a user to
increment/decrement a value in the input box. It allows users to type a value directly, or
modify an existing value by spinning with the keyboard, mouse or scrollwheel. It also has a
step feature to skip values. In addition to the basic numeric features, it also enables globalized
formatting options (ie currency, thousand separator, decimals, etc.) thus providing a
convenient internationalized masked entry box. jQueryUI provides spinner() method which
creates a spinner.
Syntax
The spinner() method can be used in two forms −
$(selector, context).spinner (options) Method
$(selector, context).spinner ("action", params) Method
$ (selector, context).spinner (options) Method
The spinner (options) method declares that an HTML element and its contents should be
treated and managed as spinner. The options parameter is an object that specifies the
appearance and behavior of the spinner elements involved.
Syntax
$(selector, context).spinner (options);
You can provide one or more options at a time using Javascript object. If there are more than
one options to be provided then you will separate them using a comma as follows −
$(selector, context).spinner({option1: value1, option2: value2..... });
Q) Explain about JQuery UI Tabs
Ans: Tabs are sets of logically grouped content that allow us to quickly flip between them to.
Tabs allow us to save space like accordions. For tabs to work properly following set of
markups needs to use − Tabs must be in a list either ordered(<ol>) or unordered(<ul>).
Each tab title must be within each <li> and wrapped by anchor (<a>) tag with an href
attribute. Each tab panel may be any valid element but it must have an id, which corresponds
to the hash in the anchor of the associated tab. jQueryUI provides us tabs () method
drastically changes the appearance of HTML elements inside the page. This method traverses
(internally in jQuery UI) HTML code and adds new CSS classes to the elements concerned
(here, the tabs) to give them the appropriate style.
Syntax
The tabs () method can be used in two forms −
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 38

$(selector, context).tabs (options) Method


$(selector, context).tabs ("action", params) Method
$ (selector, context).tabs (options) Method
The tabs (options) method declares that an HTML element and its content should be managed
as tabs. The options parameter is an object that specifies the appearance and behavior of tabs.
Syntax
$(selector, context).tabs (options);
You can provide one or more options at a time using JavaScript object. If there are more than
one options to be provided then you will separate them using a comma as follows −
$(selector, context).tabs({option1: value1, option2: value2..... });

Q) Explain about JQuery UI ToolTips


Ans: Tooltip widget of jQueryUI replaces the native tooltips. This widget adds new themes
and allows for customization. First let us understand what tooltips are? Tooltips can be
attached to any element. To display tooltips, just add titleattribute to input elements and title
attribute value will be used as tooltip. When you hover the element with your mouse, the title
attribute is displayed in a little box next to the element. jQueryUI provides tooltip() method to
add tooltip to any element on which you want to display tooltip. This gives a fade animation
by default to show and hide the tooltip, compared to just toggling the visibility.
Syntax
The tooltip() method can be used in two forms −
$(selector, context).tooltip (options) Method
$(selector, context).tooltip ("action", [params]) Method
$ (selector, context).tooltip (options) Method
The tooltip (options) method declares that a tooltip can be added to an HTML element. The
options parameter is an object that specifies the behavior and appearance of the tooltip.
Syntax
$(selector, context).tooltip(options);
You can provide one or more options at a time using Javascript object. If there are more than
one options to be provided then you will separate them using a comma as follows −
$(selector, context).tooltip({option1: value1, option2: value2..... });

Q) Explain about JQuery UI Color Animation


Ans: jQueryUI extends some core jQuery methods so that you can animate different
transitions for an element. One of them being animate method. jQueryUI extends the jQuery
animate method, to add support for animating colors. You can animate one of several CSS
properties that define an element’s colors. Following are the CSS properties that
the animate method supports. backgroundColor − Sets the background color of the element.
borderTopColor − Sets the color for top side of the element border.
borderBottomColor − Sets the color for bottom side of the element border.
borderLeftColor − Sets the color for left side of the element border.
borderRightColor − Sets the color for right side of the element border.
color − Sets the text color of the element.
outlineColor − Sets the color for the outline; used to emphasize the element.
Syntax
The following is the syntax of the jQueryUI animate method −
$( "#selector" ).animate(
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 39

{ backgroundColor: "black",
color: "white"
}
);

Q) How to Add and Remove Classes in JQuery UI


Ans: Add Class: addClass() method allow animating the changes to the CSS properties.
addClass() method add specified classes to the matched elements while animating all style
changes.
Syntax
.addClass( className [, duration ] [, easing ] [, complete ] )
Sr.No. Parameter & Description
1 className This is a String containing one or more CSS classes (separated by spaces).
2 duration This is of type Number or String, and indicates the number of milliseconds of the
effect. A value of 0 takes the element directly in the new style, without progress. Its default
value is 400.
3.easing This is of type String and indicates the way to progress in the effect. Its default
value is swing. Possible values are here.
4 complete This is a callback method called for each element when the effect is complete for
this element.
Remove Class: jQueryUI visual effects. removeClass() method removes the applied classes
from the elements. removeClass() method removes the specified classes to the matched
elements while animating all style changes.
Syntax
The removeClass() method has its basic syntax as follows −
.removeClass( className [, duration ] [, easing ] [, complete ] )
Sr.No. Parameter & Description
1 className This is a String containing one or more CSS classes (separated by
spaces) to be removed.
2 Duration This is of type Number or String, and indicates the number of milliseconds of the
effect. A value of 0 takes the element directly in the new style, without progress. Its default
value is 400.
3 easing This is of type String and indicates the way to progress in the effect. Its
default value is swing. Possible values are here.
4 complete This is a callback method called for each element when the effect is
complete for this element.

Q) Explain about Effects in jQuery UI


Ans: The effect() method, which is one of the methods used to manage jQueryUI visual
effects. effect() method applies an animation effect to the elements without having to show or
hide it.
Syntax The effect() method has the following syntax −
.effect( effect [, options ] [, duration ] [, complete ] )
Sr.No. Parameter & Description
1 effect This is a String indicating which effect to use for the transition.
2 options This is of type Object and indicates effect-specific settings and easing.
Additionally, each effect has its own set of options that can be specified common across
multiple effects described in the table jQueryUI Effects.
3 duration This is of type Number or String, and indicates the number of milliseconds of the
effect. Its default value is 400.
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 40

4 complete This is a callback method called for each element when the effect is complete for
this element.
jQueryUI Effects The following table describes the various effects that can be used with the
effects() method −
Sr.No. Effect & Description
1blind Shows or hides the element in the manner of a window blind: by moving the bottom
edge down or up, or the right edge to the right or left, depending upon the specified direction
and mode.
2 bounce Causes the element to appear to bounce in the vertical or horizontal direction,
optionally showing or hiding the element.
3 clip Shows or hides the element by moving opposite borders of the element together until
they meet in the middle, or vice versa.
4 drop Shows or hides the element by making it appear to drop onto, or drop off of, the page.

Q) Explain about JQuery Third Party Validation?


Ans: jQuery plugin that makes it easy to validate user input while keeping your HTML markup clean
from javascript code. Even though this plugin has a wide range of validation functions it's designed to
require as little network traffic as possible. This is achieved by grouping together validation functions
in "modules", making it possible to load only those functions that's needed to validate a particular
form
Example:
1. <!doctype html>
2. <html>
3. <head>
4. <meta charset="utf-8">
5. <title>Makes "field" required and a decimal number only.</title>
6. <link rel="stylesheet" href="https://jqueryvalidation.org/files/demo/site-demos.css">
7. </head>
8. <body>
9. <form id="myform">
10. <label for="field">Required, decimal number: </label>
11. <input class="left" id="field" name="field">
12. <br/>
13. <input type="submit" value="Validate!">
14. </form>
15. <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
16. <script
src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
17. <script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additionalmethods.
min.js"></script>
18. <script>
19. // just for the demos, avoids form submit
20. jQuery.validator.setDefaults({
21. debug: true,
22. success: "valid"
23. });
24. $( "#myform" ).validate({
25. rules: {
26. field: {
27. required: true,
28. number: true
29. }
30. }
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 41

31. });
32. </script>
33. </body>
34. </html>
OUTPUT:

Q) What is Regular Expression? Explain with JQuery with Plugin?


Ans: Regular expressions offer an extremely flexible and powerful way of adding validation
to your website forms. Combined with jQuery, it allows you to ensure that data sent to the
server matches all of your requirements.
Example: Program to Validate 10-digit Mobile Number using Regular Expression with
JQuery.
main.html
<html>
<head>
<title>Regular Expression with JQuery</title>
<link rel="stylesheet" type="text/css" href="styles.css"></link>
<script type="text/javascript" src="jquery-3.2.1.slim.min.js"></script>
<script type="text/javascript" src="myfirst.js"></script>
</head>
<body>
Enter Mobile Number: <input type="text" id="mn"><br>
<button id="b1">Validate</button>
</body>
</html>
myfirst.js
1. $(function() {
2. $("#b1").click( function()
3. {
4. var n= $('#mn').val();
5. var pattern = /^\d{10}$/;
6. if (pattern.test(n)) {
7. alert("Your mobile number is OK: " + n);
8. return true;
9. }
10. alert("It is not valid mobile number.input 10 digits number!");
11. return false;
12. }
13. );
14. });
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 42

III B.Sc– VI Semester –Computer Science-Cluster -2


Advance JavaScript - UNIT – IV
Q)What is AJAX? How it Works (or) How XMLHTTP Request and XML Response
Works
Ans: AJAX stands for Asynchronous JavaScript And XML. It allows you to load data in the
background and display it on your webpage, without refreshing the page. This allows you to
create websites with much richer functionality. Popular web applications like Gmail, Outlook
Web Access and Google Maps uses AJAX extensively, to provide you with a more
responsive, desktop-like experience.
Ajax Web Model: The Ajax web model is based on the traditional web model with changes to
the transmitted message on the web server and the web browser. The following diagram
presents the AJAX web model.
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 43

Steps of AJAX Operation


1. A client event occurs.
2. An XMLHttpRequest object is created.
3. The XMLHttpRequest object is configured.
4. The XMLHttpRequest object makes an asynchronous request to the Webserver.
5. The Webserver returns the result containing XML document.
6. The XMLHttpRequest object calls the callback() function and processes the result.
7. The HTML DOM is updated.

Q) How AJAX Technology Works


Ans: AJAX cannot work independently. It is used in combination with other technologies to
create interactive webpages.
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.
Q) Explain Importance of AJAX in Real Websites
Benefits of AJAX
• AJAX brings to web applications new characteristics that are not available as standard in
traditional web applications.
• Continuous uploading, time is not wasted while waiting for page redraws and reloads
• Real-time updates, certain parts of the web pages are directly updated without requiring the
whole page to update.
• Greater graphical interaction similar to desktop applications – drag and drop
• Standard mechanism for the client to interact with the server and only send small xml
fragments.

Q) Explain about XMLHTTPRequest and XMLHTTPResponse in AJAX


Ans: XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript,
and other web browser scripting languages to transfer and manipulate XML data to and from
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 44

a webserver using HTTP, establishing an independent connection channel between a


webpage's Client-Side and Server-Side.
XMLHttpRequest Methods
abort()
Cancels the current request.
getAllResponseHeaders()
Returns the complete set of HTTP headers as a string.
getResponseHeader( headerName )
Returns the value of the specified HTTP header.
open( method, URL )
open( method, URL, async )
open( method, URL, async, userName )
open( method, URL, async, userName, password )
XMLHttpRequest Properties
onreadystatechange
An event handler for an event that fires at every state change.
readyState
The readyState property defines the current state of the XMLHttpRequest object.
The following table provides a list of the possible values for the readyState property −
State Description
0 The request is not initialized.
1 The request has been set up.
2 The request has been sent.
3 The request is in process.
4 The request is completed.
Example:
ajax.html
<html>
<body>
<h1>The XMLHttpRequest Object</h1>
<p id="demo">Let AJAX change this text.</p>
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
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>
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 45

</html>
ajax_info.txt

OUTPUT:

Q) Explain Procedure to Database CURD Operations using JQuery, AJAX and PHP
Ans: CRUD means Create, Retrive, Update and Delete. Also, the purpose of using
AJAX/JQuery is that the page will not reload after an operation.

Creating our Database


First and most important step in to create our database. This will serve as storage for our
data.
1. Open phpMyAdmin.
2. Click databases, create a database and name it as "crud_bootstrap".
3. After creating a database, click the SQL and paste the below code. See image below for
detailed instruction.
Creating our Connection
Next step is to create a database connection and save it as "conn.php". This file will serve as
our bridge between our form and our database. To create the file, open your HTML code
editor and paste the code below after the tag.
<?php
//MySQLi Procedural
$conn = mysqli_connect("localhost","root","","crud_bootstrap");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 46

}
?>
Creating our Table
Next, we create our sample table. In this tutorial, we're going to create member table. We
name this as "index.php". Also included in this page is our jquery and ajax codes in the script
tag below.
Creating our Show Code
Next step is to create our show code. This is the code that we will call after an operation to
show to changes in our table. We name the code as "show_user.php".
Creating our Add Code
Next, we create our add operaiton code which will add new data into our table. We name this
as "addnew.php".
Creating our Edit Modal
Next step is to create our edit modal which we have included in our index.php. We name this
modal as "edit_modal.php".
Creating our Edit Code
Next, we create our edit code that will edit our selected row. We name this as "update.php".
Creating our Delete Code
Lastly, we create our delete code which will delete our selected row. We name this as
"delete.php".
<?php
include('conn.php');
if(isset($_POST['del'])){
$id=$_POST['id'];
mysqli_query($conn,"delete from `user` where userid='$id'");
}
?>

Q) What is JSON? How it Works (or) What is the Need of JSON in Real Websites
Ans:
JSON: JavaScript Object Notation.
JSON is a syntax for storing and exchanging data.
JSON is text, written with JavaScript object notation.
Exchanging Data
When exchanging data between a browser and a server, the data can only be text.
JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the
server. We can also convert any JSON received from the server into JavaScript objects.
This way we can work with the data as JavaScript objects, with no complicated parsing and
translations.
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 47

1. Web browser requests the content of just the part of the page that it needs to refresh.
2. Web server analyzes the received request and builds up an XML message or JSON depend
upon the user selection, which is then sent back to the web browser.
3. After the web browser receives the XML/JSON message, it parses the message in order to
update the content of that part of the page.

Q) Explain about JSON Syntax (or) JSON Data Types


Ans: The JSON syntax is a subset of the JavaScript syntax.
JSON Syntax Rules
JSON syntax is derived from JavaScript object notation syntax:
Data is in name/value pairs
Data is separated by commas
Curly braces hold objects
Square brackets hold arrays
JSON Data - A Name and a Value
JSON data is written as name/value pairs.
A name/value pair consists of a field name (in double quotes), followed by a colon, followed
by a value:
Example
"name":"John"
JSON names require double quotes. JavaScript names don't.
JSON - Evaluates to JavaScript Objects
The JSON format is almost identical to JavaScript objects.
In JSON, keys must be strings, written with double quotes:
JSON
{ "name":"John" }
In JavaScript, keys can be strings, numbers, or identifier names:
JavaScript
{ name:"John" }
JSON Values In JSON, values must be one of the following data types:
• a string
• a number
• an object (JSON object)
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 48

• an array
• a boolean
• null
In JavaScript values can be all of the above, plus any other valid JavaScript expression,
including:
• a function
• a date
• undefined
In JSON, string values must be written with double quotes:
JSON
{ "name":"John" }
In JavaScript, you can write string values with double or single quotes:
JavaScript
{ name:'John' }
JSON Uses JavaScript Syntax Because JSON syntax is derived from JavaScript object
notation, very little extra software is needed to work with JSON within JavaScript.
With JavaScript you can create an object and assign data to it, like this:
Example
var person = { "name":"John", "age":31, "city":"New York" };
You can access a JavaScript object like this:
Example
person.name; // returns John
It can also be accessed like this:
Example
person["name"]; // returns John
Data can be modified like this:
Example
person.name = "Gilbert";
It can also be modified like this:
Example
person["name"] = "Gilbert";
You will learn how to convert JavaScript objects into JSON later in this tutorial.
JavaScript Arrays as JSON
The same way JavaScript objects can be used as JSON, JavaScript arrays can also be used as
JSON. You will learn more about arrays as JSON later in this tutorial.
JSON Files
The file type for JSON files is “.json”

Q) How to Read JSON Objects


Ans: Creating Simple Objects JSON objects can be created with JavaScript. Let us see the
various ways of creating JSON objects using JavaScript −
Creation of an empty Object –
var JSONObj = {};
Creation of a new Object −
var JSONObj = new Object();
Creation of an object with attribute bookname with value in string, attribute price with
numeric value. Attribute is accessed by using '.' Operator
var JSONObj = { "bookname ":"VB BLACK BOOK", "price":500 };
This is an example that shows creation of an object in javascript using JSON, save the below
code as json_object.htm −
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 49

<html>
<head>
<title>Creating Object JSON with JavaScript</title>
<script language = "javascript" >
var JSONObj = { "name" : "tutorialspoint.com", "year" : 2005 };
document.write("<h1>JSON with JavaScript example</h1>");
document.write("<br>");
document.write("<h3>Website Name = "+JSONObj.name+"</h3>");
document.write("<h3>Year = "+JSONObj.year+"</h3>");
</script>
</head>
<body>
</body>
</html>
Now let's try to open Json Object using IE or any other javaScript enabled browser. It
produces the following result –

Q) Explain about JSON Array


Ans: JSON array represents ordered list of values. JSON array can store multiple values. It
can store string, number, boolean or object in JSON array. In JSON array, values must be
separated by comma.The [ (square bracket) represents JSON array. Let's see a simple JSON
array example having 4 objects.
{"employees":[
{"name":"Ram", "email":"ram@gmail.com", "age":23},
{"name":"Shyam", "email":"shyam23@gmail.com", "age":28},
{"name":"John", "email":"john@gmail.com", "age":33},
{"name":"Bob", "email":"bob32@gmail.com", "age":41}
]}

Q) Explain JSON Vs XML


Ans:
No. JSON XML
1) JSON stands for JavaScript Object Notation. XML stands for eXtensible Markup
Language.
2) JSON is simple to read and write. XML is less simple than JSON.
3) JSON is easy to learn. XML is less easy than JSON.
4) JSON is data-oriented. XML is document-oriented.
5) JSON doesn't provide display capabilities.
XML provides the capability to display data because it is a markup language.
6) JSON supports array. XML doesn't support array.
7) JSON is less secured than XML. XML is more secured.
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 50

8) JSON files are more human readable than XML.XML files are less human readable.
9) JSON supports only text and number data type. XML support many data types such as
text, number, images, charts, graphs etc. Moreover, XML offeres options for
transferring the format or structure of the data with actual data.

Q) How to Read JSON Object using JQuery? (or) Explain about parse() and stringify()
methods
Ans: The JSON.parse()method first validates the JSON-formatted text string and then converts it into a
JavaScript object. Using this object we can access the properties of class.
<html>
<head>
<title>Reading Data From JSON using JQuery</title>
</head>
<body>
<h1> Reading Data</h1>
<p id="demo"> </p>
<script type="text/javascript">
var text = '{"name": "kumar","email": "kumar@gmail.com"}';
var ptxt= JSON.parse(text);
document.getElementById('demo').innerHTML=ptxt.email;
</script>
</body>
</html>

Stringify
A common use of JSON is to exchange data to/from a web server. When sending data to a
web server, the data has to be a string. Convert a JavaScript object into a string with
JSON.stringify().
<html>
<head>
<title>Reading Data From JSON using JQuery</title>
</head>
<body>
<h1> Reading Data with Stringify</h1>
<p id="demo"> </p>
<script type="text/javascript">
var obj = { "name":"John", "age":30, "city":"New York"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>
</body>
</html>
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 51

Q) Explain Difference Between JSON and XML


Ans: Both JSON and XML can be used to receive data from a web server. For AJAX
applications, JSON is faster and easier than XML: Using XML
• Fetch an XML document
• Use the XML DOM to loop through the document
• Extract values and store in variables Using JSON
• Fetch a JSON string
• JSON.Parse
the JSON string The biggest difference is: XML has to be parsed with an XML
parser. JSON can be parsed by a standard JavaScript function. So XML is much more
difficult to parse than JSON. JSON is parsed into a ready-to-use JavaScript object.
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 52

UNIT-V
Q) What is AngularJS
Ans: AngularJS is a JavaScript framework. It is a library written in JavaScript.
AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
AngularJS is an open source web application framework. It was originally developed in 2009
by Misko Hevery and Adam Abrons. It is now maintained by Google. Its latest version is
1.4.3.
Q) Explain about Need of AngularJS in Real World
Ans: AngularJS is a very powerful JavaScript Framework. It is used in Single Page
Application (SPA) projects. It extends HTML DOM with additional attributes and makes it
more responsive to user actions. AngularJS is open source, completely free, and used by
thousands of developers around the world.
• AngularJS is a powerful JavaScript based development framework to create RICH Internet
Application(RIA).
• AngularJS provides developers options to write client side application (using JavaScript) in
a clean MVC(Model View Controller) way.
• Application written in AngularJS is cross-browser compliant. AngularJS automatically
handles JavaScript code suitable for each browser.
• AngularJS is open source, completely free, and used by thousands of developers around
the world. It is licensed under the Apache License version 2.0.

Q) Explain about AngularJS MVC Architecture


Ans: MVC stands for Model View Controller. It is a software design pattern for developing
web applications. It is very popular because it isolates the application logic from the user
interface layer and supports separation of concerns. The MVC pattern is made up of the
following three parts:
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 53

Model: It is responsible for managing application data. It responds to the requests from view
and to the instructions from controller to update itself.
View: It is responsible for displaying all data or only a portion of data to the users. It also
specifies the data in a particular format triggered by the controller's decision to
present the data. They are script-based template systems such as JSP, ASP, PHP and very
easy to integrate with AJAX technology.
Controller: It is responsible to control the relation between models and views. It responds to
user input and performs interactions on the data model objects. The controller receives input,
validates it, and then performs business operations that modify the state of the data model.

Q) How to Download AngularJS


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

This screen gives various


options of using Angular JS as follows −
Downloading and hosting files locally
There are two different options legacy and latest. The names itself are self-descriptive.
legacy has version less than 1.2.x and latest has 1.5.x version. We can also go with the
minified, uncompressed or zipped version.
CDN(Content Delivery Network) access − You also have access to a CDN. The CDN will
give you access around the world to regional data centers that in this case, Google host.

Q) Explain about Simple AngularJS with Example


Ans: An AngularJS application consists of following three important parts −
ng-app − This directive defines and links an AngularJS application to HTML.
ng-model − This directive binds the values of AngularJS application data to HTML input
controls.
ng-bind − This directive binds the AngularJS Application data to HTML tags.
Steps to create AngularJS Application
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 54

Step 1 − Load framework


Being a pure JavaScript framework, It can be added using <Script> tag.
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
Step 2 − Define AngularJS Application using ng-app directive
<div ng-app = "">
...
</div>
Step 3 − Define a model name using ng-model directive
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
Step 4 − Bind the value of above model defined using ng-bind directive.
<p>Hello <span ng-bind = "name"></span>!</p>
Steps to run AngularJS Application
Use above mentioned three steps in an HTML page.
<html>
<head>
<title>AngularJS First Application</title>
<script src = "angular-1.6.7/angular.min.js"></script>
</head>
<body>
<h1>Sample Application</h1>
<div ng-app = "">
<p>Enter your College Name <input type = "text" ng-model = "name"></p>
<p>Welcome to: <b><span ng-bind = "name"></span></b></p>
</div>
</body>
</html>

Q) Explain about AngularJS build in Directives


Ans: AngularJS directives are used to extend HTML. These are special attributes starting
with ngprefix.
We're going to discuss following directives −
• ng-app − This directive starts an AngularJS Application.
• ng-init − This directive initializes application data.
• ng-model − This directive binds the values of AngularJS application data to HTML input
controls.
• ng-repeat − This directive repeats html elements for each item in a collection.
ng-app directive ng-app directive starts an AngularJS Application. It defines the root
element. It automatically initializes or bootstraps the application when web page containing
AngularJS Application is loaded.
<div ng-app = "">
...
</div>
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 55

ng-init directive
ng-init directive initializes an AngularJS Application data. It is used to put values to the
variables to be used in the application. In following example, we'll initialize an array of
countries. We're using JSON syntax to define array of countries.
<div ng-app = "" ng-init = courses = [{locale:'Maths-PhysicsComputer-
Science',name:'MPCS'},
{locale:'Maths-Stats-ComputerScience',name:'MSCS'},
{locale:'Maths-Electronics-ComputerScience',name:'MECS'}]" >
...
</div>
ng-model directive
This directive binds the values of AngularJS application data to HTML input controls. In
following example, we've defined a model named "name".
Example
<html>
<head>
<title>AngularJS Directives</title>
<script src = "angular-1.6.7/angular.min.js"></script>
</head>
<body>
<h1>Directives Example</h1>
<div ng-app = "" ng-init = "courses = [{locale:'Maths-PhysicsComputer-
Science',name:'MPCS'},
{locale:'Maths-Stats-ComputerScience',name:'MSCS'},
{locale:'Maths-Electronics-ComputerScience',name:'MECS'}]">
<p>Enter College Name: <input type = "text" ng-model = "name"></p>
<p>Welcome <span ng-bind = "name"></span></p>
<p>List of Courses with Subjects:</p>
<ol>
<li ng-repeat = "course in courses">
{{ 'Group: ' + course.name + ', Subjects: ' + course.locale }}
</li>
</ol>
</div>
</body>
</html>

Q) Explain about Expressions in AngularJS (OR) How to write Expressions in


AngularJS
Ans: AngularJS expressions can be written inside double braces: {{ expression }}.
AngularJS expressions can also be written inside a directive: ng-bind="expression".
AngularJS will resolve the expression, and return the result exactly where the expression is
written. Using numbers <p>Expense on Books : {{cost * quantity}} Rs</p> Using strings
<p>Hello {{student.firstname + " " + student.lastname}}!</p>
Using object
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 56

<p>Roll No: {{student.rollno}}</p>


Using array
<p>Marks(Math): {{marks[3]}}</p>
Example
<html>
<head>
<title>AngularJS Expressions</title>
<script src = "angular-1.6.7/angular.min.js"></script>
</head>
<body>
<h1>Expression Examples</h1>
<div ng-app = "" ng-init = "quantity = 1;cost = 30; student =
{firstname:'John',lastname:'Peter',rollno:101};marks = [80,90,75,73,60]">
<p>Hello {{student.firstname + " " + student.lastname}}!</p>
<p>Expense on Books : {{cost * quantity}} Rs</p>
<p>Roll No: {{student.rollno}}</p>
<p>Marks(Math): {{marks[3]}}</p>
</div>
</body>
</html>

Q) Explain about AngularJS Modules (OR) How to Create Modules in AngularJS


Ans: AngularJS supports modular approach. Modules are used to separate logics say services,
controllers, application etc. and keep the code clean. n this example we're going to create two
modules.
Application Module − used to initialize an application with controller(s).
Controller Module − used to define the controller.
Application Module mainApp.js
var mainApp = angular.module("mainApp", []);
Here we've declared an application mainApp module using angular.module function. We've
passed an empty array to it. This array generally contains dependent modules.
Controller Module studentController.js
mainApp.controller("studentController", function($scope) {
$scope.student = {
firstName: "LAKSHMI",
lastName: "NARAYANA",
fees:700,
subjects:[
{name:'Physics',marks:70},
{name:'Chemistry',marks:80},
{name:'Math',marks:65},
{name:'English',marks:75},
{name:'Hindi',marks:67}
],
fullName: function() {
var studentObject;
studentObject = $scope.student;
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 57

return studentObject.firstName + " " + studentObject.lastName;


}
};
});

Q) Explain about Controllers in AngularJS


Ans: AngularJS applications are controlled by controllers. The ng-controller directive
defines the application controller. A controller is a JavaScript Object, created by a standard
JavaScript object constructor.
<html>
<head>
<title>Controller Example in AngularJS</title>
<script src = "angular-1.6.7/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Peter";
});
</script>
</body>
</html>

Application explained:
The AngularJS application is defined by ng-app="myApp". The application runs inside
the <div>.
The ng-controller="myCtrl" attribute is an AngularJS directive. It defines a controller.
The myCtrl function is a JavaScript function.
AngularJS will invoke the controller with a $scope object.
In AngularJS, $scope is the application object (the owner of application variables and
functions).
The controller creates two properties (variables) in the scope (firstName and lastName).
The ng-model directives bind the input fields to the controller properties (firstName and
lastName).

Q) Explain about Scope in AngularJS (OR) Explain about $scope Variable


Ans: Scope is a special javascript object which plays the role of joining controller with the
views. Scope contains the model data. In controllers, model data is accessed via $scope
object.
Following are the important points to be considered in above example.
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 58

$scope is passed as first argument to controller during its constructor definition.


$scope.message and $scope.type are the models which are to be used in the HTML page.
We've set values to models which will be reflected in the application module whose
controller is shapeController.
We can define functions as well in $scope.
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller("shapeController", function($scope) {
$scope.message = "In shape controller";
$scope.type = "Shape";
});
mainApp.controller("circleController", function($scope) {
$scope.message = "In circle controller";
});
</script>

Q) Explain about Dependency Injection in AngularJS


Ans: Dependency Injection is a software design pattern in which components are given their
dependencies instead of hard coding them within the component. This relieves a component
from locating the dependency and makes dependencies configurable. This helps in making
components reusable, maintainable and testable. AngularJS provides a supreme Dependency
Injection mechanism. It provides following core components which can be injected into each
other as dependencies.
• value
• factory
• service
• provider
• constant
value: value is simple javascript object and it is used to pass values to controller during
config phase.
var mainApp = angular.module("mainApp", []);
//create a value object as "defaultInput" and pass it a data.
mainApp.value("defaultInput", 5);
factory: factory is a function which is used to return value. It creates value on demand
whenever a service or controller requires. It normally uses a factory function to calculate and
return the value.
factory.multiply = function(a, b) {
return a * b
}
return factory;
service: service is a singleton javascript object containing a set of functions to perform
certain tasks. Services are defined using service() functions and then injected into controllers.
mainApp.service('CalcService', function(MathService){
this.square = function(a) {
return MathService.multiply(a,a);
}
});
Provider: provider is used by AngularJS internally to create services, factory etc. during
config phase(phase during which AngularJS bootstraps itself). Below mention script can be
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 59

used to create MathService that we've created earlier. Provider is a special factory method
with a method get() which is used to return the value/service/factory.
Constant: constants are used to pass values at config phase considering the fact that value
can not be used to be passed during config phase.
mainApp.constant("configParam", "constant value");

Q) Explain about bootstrapping AngularJS data bindings


Ans: Data binding is a very useful and powerful feature used in software development
technologies. It acts as a bridge between the view and business logic of the application.
AngularJS follows Two-Way data binding model.
One-Way Data Binding
The one-way data binding is an approach where a value is taken from the data model and
inserted into an HTML element. There is no way to update model from view. It is used in
classical template systems. These systems bind data in only one direction.

Two-Way Data Binding


Data-binding in Angular apps is the automatic synchronization of data between the model
and view components. Data binding lets you treat the model as the single-source-of-truth in
your application. The view is a projection of the model at all times. If the model is changed,
the view reflects the change and vice versa.
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 60

Q) Explain about $watch scope(OR) AngularJS $watch


Ans: The $scope.watch() function creates a watch of some variable. When you register a
watch you pass two functions as parameters to the $watch() function:
A value function A listener function Here is an example:
$scope.$watch(function() {},
function() {}
);
The first function is the value function and the second function is the listener function.
Example:
watch.js
var app = angular.module("helloApp", []);
app.controller("helloCtrl", function ($scope) {
$scope.myName = "";
$scope.$watch("myName", function (newValue, oldValue) {
if ($scope.myName.length > 5) {
$scope.updated_info = "\"" + $scope.myName + "\" has length > 5";
} else {
$scope.updated_info = "\"" + $scope.myName + "\" has length <= 5";
}
});
});
watchexample.html
<html>
<head>
<title>AngularJS Watch Example</title>
<script src = "angular-1.6.7/angular.min.js"></script>
<script src = "watch.js"></script>
</head>
<body>
<h1 align="center"> $watch example</h1>
<div ng-app="helloApp" ng-controller="helloCtrl">
<p>Name:
<input type="text" placeholder="your name" ng-model="myName">
</p>
<h1>Hello {{myName}}</h1>
<h2>{{updated_info}}</h2>
</body>
</html>

Q) Explain about Filters in AngularJS


Ans: Filters are used to change modify the data and can be clubbed in expression or
directives using pipe character. Following is the list of commonly used filters.
Sr.No. Name Description
1 uppercase converts a text to upper case text.
2 lowercase converts a text to lower case text.
3 currency formats text in a currency format.
4 filter filter the array to a subset of it based on provided criteria.
5 orderby orders the array based on provided criteria.
Example
<html>
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 61

<head>
<title>Angular JS Filters</title>
<script src = "angular-1.6.7/angular.min.js"></script>
</head>
<body>
<h2>AngularJS Filters Example</h2>
<div ng-app = "mainApp" ng-controller = "studentController">
<table border = "0">
<tr>
<td>Enter fees: </td>
<td><input type = "text" ng-model = "student.fees"></td>
</tr>
</table>
<br/>
<table border = "0">
<tr>
<td>fees: </td><td>{{student.fees | currency}}
</td>
</tr>
</table>
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope) {
$scope.student = {
fees:500
};
});
</script>
</body>
</html>

Q) Explain about AngularJS Events Directives (OR) Explain Events in AngularJS


Ans: AngularJS includes certain directives which can be used to provide custom behavior on
various DOM events, such as click, dblclick, mouseenter etc. The following table lists
AngularJS event directives.
ng-blur
ng-change
ng-click
ng-copy
ng-cut
ng-dblclick
ng-focus
ng-keydown
ng-keypress
ng-keyup
ng-mousedown
ng-mouseenter
ng-mouseleave
ng-mousemove
ng-mouseover
ng-mouseup
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 62

ng-paste
Example:
<html>
<head>
<title>AngularJS Events Example</title>
<script src = "angular-1.6.7/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1 ng-mousemove="count = count + 1">Mouse Over Me!</h1>
<h2>{{ count }}</h2>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
});
</script>
</body>
</html>

Q) Explain about AngularJS with AJAX? (OR) Explain about ng-repeat (OR) How to
combine AngularJS with AJAX/JSON (OR) How to work with AngularJS with JSON
arrays.
Ans: AngularJS provides $https: control which works as a service to read data from the
server. The server makes a database call to get the desired records. AngularJS needs data in
JSON format. Once the data is ready, $https: can be used to get the data from server in the
following manner.
Example
testajax.html
<html>
<head>
<title>Angular JS AJAX and JSON</title>
</head>
<body>
<center>
<h2>AngularJS AJAX and JSON Application</h2>
<div ng-app = "" ng-controller = "studentController">
<table>
<tr>
<th>Name</th>
<th>Roll No</th>
<th>Percentage</th>
</tr>
<tr ng-repeat = "student in students">
<td>{{ student.Name }}</td>
<td>{{ student.RollNo }}</td>
<td>{{ student.Percentage }}</td>
</tr>
</table>
</div>
<script>
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 63

function studentController($scope,$http) {
var url = "data.txt";
$http.get(url).then( function(response) {
$scope.students = response.data;
});
}
</script>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</center>
</body>
</html>
data.txt
[
{
"Name" : "Mahesh Parashar",
"RollNo" : 101,
"Percentage" : "80%"
},
{
"Name" : "Dinkar Kad",
"RollNo" : 201,
"Percentage" : "70%"
},
{
"Name" : "Robert",
"RollNo" : 191,
"Percentage" : "75%"
},
{
"Name" : "Julian Joe",
"RollNo" : 111,
"Percentage" : "77%"
}
]

Here, the file data.txt contains student records. $https: service makes an ajax call and sets
response to its property students. students model can be used to draw tables in HTML.
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 64

Q) Explain steps to Create Registration form and login form using AngularJS
Ans:

1. Create the html extended angularJS forms as separate files and


2. Add the Controller and give the functionalty for the register button
3. Then write the validation code with regular expression
4. Store the details in Database of file system
5. Write the login form code and validate username,password with the database or file system
6. If true user and password Show the welcome else error page.

Q) Explain CURD Operations Using AngularJS


Ans: Create, Read, Update, Delete Using Angularjs
Create- creating the new row in database
Read- reading a row from the database Update- modify as requested in the row Delete –
deleting the row.
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 65

Q) Explain about Animation in AngularJS


Ans: An animation is when the transformation of an HTML element gives you an illusion of
motion. AngularJS provides the angular-animate.js file in its liabrary, we can make use of this
file and able to write the animation functionality.
Example:
<html>
<title>AngularJS Animate Example</title>
<script src = "angular-1.6.7/angular.min.js"></script>
<script src = "angular-1.6.7/angular-animate.js"></script>
</head>
<style>
div {
transition: all linear 0.5s;
background-color: lightblue;
height: 100px;
width: 100%;
position: relative;
top: 0;
left: 0;
}
.ng-hide {
height: 0;
width: 0;
background-color: transparent;
top:-200px;
left: 200px;
}
</style>
<body ng-app="ngAnimate">
<h1>Hide the DIV: <input type="checkbox" ng-model="myCheck"></h1>
<div ng-hide="myCheck"></div>
</body>
</html>
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 66

Q) Explain about AngularJS Validation


Ans: Form Validation
AngularJS offers client-side form validation. AngularJS monitors the state of the form and
input fields (input, textarea, select), and lets you notify the user about the current state.
AngularJS also holds information about whether they have been touched, or modified, or not.
Example:
<html>
<title>Angular JS Filters</title>
<script src = "angular-1.6.7/angular.min.js"></script>
<body ng-app="">
<p>Try writing in the input field:</p>
<form name="myForm">
<input name="myInput" ng-model="myInput" required>
</form>
<p>The input's valid state is:</p>
<h1>{{myForm.myInput.$valid}}</h1>
</body>
</html>

Q) What is $q and promise


Ans: A promise is a special type of Object that we can either use, or construct ourselves to
handle asynchronous tasks. We deem them promises because we are “promised” a result at a
future point in time. For example an HTTP call could complete in 200ms or 400ms, a
promise will execute when resolved. let promise = $q((resolve, reject) => {
if (/* some async task is all good */) {
resolve('Success!');
} else {
reject('Oops... something went wrong');
}
});
promise.then(data => {
console.log(data);
});
A promise has three states, pending, resolved or rejected. Using $qin Angular, we can
construct our own promises, however let’s look at the ES2015 Promise Object first to get
familiar on how to create one.
Q) Explain about AngularJS Factories and Services (OR) Explain Difference Between
Factories and Services
Ans: AngularJS supports the concepts of "Separation of Concerns" using services
architecture. Services are javascript functions and are responsible to do a specific tasks only.
This makes them an individual entity which is maintainable and testable. Controllers, filters
can call them as on requirement basis. Services are normally injected using dependency
injection mechanism of AngularJS. AngularJS provides many inbuilt services for example,
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 67

$https:, $route, $window, $location etc. Each service is responsible for a specific task for
example, $https: is used to make ajax call to get the server data. $route is used to define the
routing information and so on. Inbuilt services are always prefixed with $ symbol. There are
two ways to create a service. Factory service
Using factory method
Using factory method, we first define a factory and then assign method to it.
var mainApp = angular.module("mainApp", []);
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b
}
return factory;
});
Using service method
Using service method, we define a s ervice and then assign method to it. We've also injected
an already available service to it.
mainApp.service('CalcService', function(MathService){
this.square = function(a) {
return MathService.multiply(a,a);
}
});

Q) Explain about Custom Directives in AngularJS


Ans: Custom directives are used in AngularJS to extend the functionality of HTML. Custom
directives are defined using "directive" function. A custom directive simply replaces the
element for which it is activated. AngularJS application during bootstrap finds the matching
elements and do one time activity using its compile() method of the custom directive then
process the element using link() method of the custom directive based on the scope of the
directive. AngularJS provides support to create custom directives for following type of
elements.
Element directives − Directive activates when a matching element is encountered.
Attribute − Directive activates when a matching attribute is encountered.
CSS − Directive activates when a matching css style is encountered.
Comment − Directive activates when a matching comment is encountered.
Understanding Custom Directive
Define custom html tags.
<student name = "Mahesh"></student><br/>
<student name = "Piyush"></student>

Q) Explain about Custom Providers in AngularJS


Ans: The provider() function allows us to create a configurable service where we can set
input per application for the service created using the provider (). For example, if we need to
set API key to access a service on the application level, we can set that in the module config
and pass input to the provider using the $provide service. All the others ways to create
services internally use the $provide service.
1. A provider function must have a $get function. To create a simple service using the
provider(), we need to perform following five steps:
2. Inject the $provide service in the app config method
ADV JAVASCRIPT 3RD BSC CLUSTER-2 BY LAKSHMINARAYANA Y SRI SAIKRUPA DEGREE COLLEGE 68

3. Create a provider using the provider() function


4. Pass two parameters to the provider() function: the name of the service and a function
5. The provider function must contain a $get function
6. Return an object literal from the $get function
So we can conclude that using the factory() function to create a service is a simplified syntax
of
$provide.factory().

Q) Explain about AngularJS Routing


Ans: The ngRoute module helps your application to become a Single Page Application.
If you want to navigate to different pages in your application, but you also want the
application to be a SPA (Single Page Application), with no page reloading, you can use
the ngRoute module.
The ngRoute module routes your application to different pages without reloading the entire
application.

Q) Explain bout AngularUI Routing


Ans: Angular-ui router organizes them in to states. It allows us to create more powerful
nested views. So what is a state, well it is just a way to define your view. An angular-ui router
state has the following characteristics
Each state must have a unique name.
A state must have a URL, this identifies the state but it does not refer to any physical
content.
A state has a template or a templateUrl, this URL needs to point to physical content which
is called a HTML partial.
States can also optionally have controller associated with them.

=======END=======

S-ar putea să vă placă și