You are on page 1of 130

Advanced Java Script

List of Questions

Unit – I: JQuery – Basics

Essay Questions:
1. Discuss about jQuery.
2. Explain the following in JQuery.
(a) Functions (b) Arguments (c) Scope (d) Built – in function (d) Callback functions
3. Explain in detail about jQuery selectors with examples.
4. Explain jQuery DOM attributes with example each.
5. List out methods to manipulate JQuery DOM attributes and describe them with suitable
examples.
6. Briefly explain about JQuery – DOM Traversing.
7. List out JQuery DOM Traversing Methods and describe them.

Short Answer Questions:


1. Explain the following in JQuery.
(a) String (b) Numbers (c) Boolean (d) Objects (e) Arrays
2. What are the advantages and disadvantages of an JQuery?

Unit – II: jQuery – CSS Methods

Essay Questions:
1. How to apply and return CSS properties using jQuery CSS Methods. Explain with an example.
2. List out jQuery dimension methods and display all the dimensions using related methods.
3. How to set and return element width in jQuery. Explain with an example.
4. How to set and return element height in JQuery. Explain with an example.
5. Explain in detail about DOM Content manipulation in JQuery with an example.
6. Explain in detail about DOM Element Replacement in JQuery with an example.
7. Explain how to remove DOM Element in JQuery with an example.
8. Explain how to insert DOM Element in JQuery with an example.
9. List out various types of DOM event in JQuery and describe them.
10. How to establish event handlers on DOM elements in JQuery. Explain with an example.
11. How to remove event handlers that are established on DOM elements in JQuery. Explain with an
example.
12. Explain how to hide and show the elements in JQuery with an example.
13. Explain how to apply slide effect for the elements in JQuery with an example.
14. Explain how to apply fade effect for the elements in JQuery with an example.
15. Explain how to apply custom animations for the elements in JQuery with an example.

1
Advanced Java Script

Short Answer Questions:


1. List out the JQuery CSS methods and describe them.
2. List out the JQuery DOM manipulation methods and describe them.
3. List out the JQuery Event Object methods and describe them.
4. List out the JQuery Event Attributes and describe them.
5. List out the JQuery Effect methods and describe them.

Unit – III: Intro to JQuery UI

Essay Questions:
1. How to download JQuery UI.
2. Give the syntax of JQuery UI Interaction methods.
3. Give the syntax of JQuery UI Widget methods.
4. Explain about consuming JQuery plugins from third party websites with an example.
5. Explain about JQuery validation plug – in.

Short Answer Questions:


1. What is the need of JQuery UI real websites?
2. Define JQuery UI and describe the features of JQuery UI.
3. List out the methods of JQuery UI plugin and describe them.
4. Give the syntax of JQuery UI Effect methods.
5. Give the syntax of JQuery UI utility methods.
6. Explain about JQuery themes.
7. How to Customize JQuery UI widgets/ plug – ins.

Unit – IV: Intro to AJaX

Essay Questions:
1. Explain how to insert, delete and update data into database using JQuery-Ajax.
2. Explain about grid development using JQuery-Ajax.
3. Explain about JSON objects.

Short Answer Questions:


1. Explain the need of AJAX in real websites.
2. How to get database data using JQuery-AJAX?
3. Discuss bout the syntax of JSON.
4. Explain about reading JSON objects using JQuery.
5. Explain about JSON arrays.
6. List out the JQuery Ajax methods and describe them.

2
Advanced Java Script

Unit – V: Intro to AngularJS

Essay Questions:
1. How to download AngularJS.
2. Explain about AngularJS Expressions?
3. Explain about AngularJS Modules?
4. Explain about AngularJS Controllers?
5. Explain about AngularJS Scope?
6. Explain about AngularJS Dependency Injection?
7. Explain about AngularJS Filters?
8. Explain about AngularJS Events?
9. Explain about AngularJS Ajax?
10. Explain about AngularJS Routing?
11. Explain about AngularJS Validation?
12. Explain about AngularJS $q?
13. Explain how to create AngularJS registration form?
14. Explain how to create AngularJS login form?
15. Explain about AngularJS CRUD Operations?

Short Answer Questions:


1. Explain the syntax of AngularJS with an example.
2. List out AngularJS built-in directives and describe them?
3. Explain about AngularJS Custom Services and Custom factories.
4. Explain about AngularJS Custom Directives?
5. Explain about AngularJS Data Binding?
6. Explain about AngularJS ng-repeat?
7. Explain about AngularJS Animation?
8. Explain about AngularJS $watch?

Programs

1. Using JQuery find all textareas and makes a border. Then adds all paragraphs to the JQuery
object to set their borders red.
2. Using JQuery add the class “w3r_font_color”and w3r_background to the last paragraph element.
3. Using JQuery add a new class to an element that already has a class.
4. Using JQuery insert some HTML after all paragraphs.
5. Using JQuery insert a DOM element after all paragraphs.
6. Convert three headers and content panels into an accordion. Initialize the accordion and specify
the animate option.
7. Convert three headers and content panels into an accordion. Initialize the accordion and specify
the height.
8. Create a pre-populated list of values and delay in milliseconds between a keystroke occurs and
a search is performed.
9. Initialize the button and specify the disable option.

3
Advanced Java Script

10. Initialize the button and specify an icon on the button.


11. Initialize the button and do not show the label.
12. Create a simple JQuery UI Datepicker. Now pick a date and store it in a textbox.
13. Initialize the datepicker and specify a text to display for the week of the year column heading.

4
Advanced Java Script

Unit – I
JQuery – Basics
Essay Questions
Q1. Discuss about JQuery.
JQuery is fast, lightweight and feature – rich client side Java Script Library / Framework which
helps in to traverse HTML DOM, make animations, add Ajax interaction, manipulate the page
content, change the style and provide cool UI effect.

Advantages of JQuery:
a) Easy to use and learn.
b) Easily expandable.
c) Cross-browser support (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+)
d) Easy to use for DOM manipulation and traversal.
e) Large pool of built in methods.
f) AJAX Capabilities.
g) Methods for changing or applying CSS, creating animations.
h) Event detection and handling.

i) Tons of plug-ins for all kind of needs.


Downloading JQuery:
JQuery library comes in two different versions.
1) Production.

2) Deployment.
The production version is quite useful at development time as JQuery is open source and it is
possible to make changes in production version.
But the deployment version is minified version or compressed version so it is impossible to
make changes in it. Because it is compressed, its size is very less than the production version and so
it loads quickly and saves bandwidth.
Both versions can be downloaded from JQuery.com. There are two ways to download JQuery.
1. The JQuery library is a single Java Script file and it can be referenced with the HTML
<script> tag (<script> tag should be inside the <head> section):
<head>
<script src=”jquery-3.3.1.min.js”></script>
</head>
2. The second way is to include it from a CDN.
Content delivery network or content distribution network (CDN) is a large distributed
system of servers deployed in multiple data centers across the Internet. The goal of a CDN is
to serve content to end-users with high availability and high performance.

5
Advanced Java Script

6
Advanced Java Script

There are 2 popular JQuery CDNs


1. Google.
2. Microsoft.
Advantages of using CDN:
a) It reduces the load from your server.
b) It saves bandwidth. JQuery framework will load faster from these CDN.
c) The most important benefit is it will be cached, if the user has visited any site which is
using JQuery framework from any of these CDN.
Loading JQuery from CDN:
1. From Google CDN
<script type=”text/javascript”
src=”http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js”>
</script>
2. Form Microsoft CDN
<script type=”text/javascript” src=”http://ajax.microsoft.com/ajax/jquery/1.9.1.min.js>
</script>
Syntax of JQuery:
The JQuery syntax is made for selecting HTML elements and performing some action on the
element(s).
Basic syntax is: $(selector).action()
a) A $ sign to define / access JQuery
b) A (selector) to “query (or find)” HTML elements
c) A JQuery action() to be performed on the element(s)
Examples:
a) $ (this).hide() – hides the current element.
b) $(“p”).hide() – hides all <p> elements.
c) $(“.test”).hide() - hides all element with class=”test”.
d) $(“#test”).hide() – hides the element with id=”test”.
The starting point of JQuery code execution is $(document).ready() function which is executed
when DOM is loaded.
$(document).ready(function(){//JQuery methods go here..});
Dollar Sign is nothing but it’s an alias for JQuery and $ sign can be replaced with “JQuery” keyword.
JQuery(document).ready(function(){ });

Q2. Explain the following in JQuery.


a) Functions b) Arguments c) Scope d) Built-in functions e) Callback functions.

7
Advanced Java Script

a) Functions:
A function in java script can be either named or anonymous.
A named function can be defined using function keyword as follows:
Function named() {//do some stuff here}
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 use to anonymous functions very frequently as follows:
$(documents).ready(function(){
//do some stuff here
});

b) Arguments:
JavaScript variable argument is a kind of array which has length property.
Example:
Function func(x){
Console. (typeof x, arguments.length);
}
func( ); //”undefinded”,0
func(1); //”number”,1
func(“1”, “2”, “3”); //”string”, 3
The arguments object also has a callee property, which refers to the inside of the function. For
example:
Function func( ){
Return arguments.callee;
}
func( ); //func

c) Scope:
The scope of a variable is the region of your program in which it is defined. Java Script variable will
have only two scopes.
Global Scope: A global variable has global scope which means it is defined everywhere in java
script code.
Local Scope: A local variable will be visible only within a function where it is defined. Function
parameters are always local to that function. Within body of function, a local variable takes
precedence over a global variable with the same name:

8
Advanced Java Script

var myVar=”global”; //Declare a global variable


function( )
var myVar “local”; //Declare a local variable
document.write(my Var); //local

d) Built in functions:
JavaScript built-in functions can be used to manipulate string numbers and dates.

Method Description
charAt( ) Returns the character at the specified index.
concat( ) Combines the text of two strings and returns a new string.
forEach( ) Calls a function for each element in the array.
IndexOf( ) Returns the index within the calling string object of the first occurrence of the
specified value, or – 1 if not found.
length( ) Returns the length of the string.
pop( ) Removes the last element from an array and returns that element.
push( ) Adds one or more elements to the end of an array and returns the new length of
the array
reverse( ) Reverses the order of the elements of an array, the first becomes the last, and the
last becomes the first.
sort ( ) Sorts the elements of an array
substr ( ) Returns the characters in a string beginning at the specified location through the
specified number of characters.
toLowerCase( ) Returns the calling string value converted to lower case.
tostring( ) Returns the string representation of the number’s value.
toUpperCase( ) Returns the calling string value converted to uppercase.

e) Callback Functions:
JavaScript statements are executed line by line. But, since JQuery effect takes some time to
finish the next line code may execute while the previous effect is still running. To prevent this from
happening JQuery provides a callback function for each effect method.
A callback function is a function that is executed once the effect is complete. The callback
function is passed as an argument to the effect methods and they typically appear as the last
argument of the method. For example, the basic syntax of the JQuery slideToggle( ) effect method
with a callback function can be given with
$(selector).slideToggle(duration, callback);

9
Advanced Java Script

Consider the following example in which the slideToggle( ) and alert( ) statements are
placed next to each other. Here, the alert will be displayed immediately once you click the trigger
button without waiting for slide toggle effect to complete.

<script type=”text/javascript”>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“p”).slideToggle(“slow”);
alert(“The slide toggle effect has completed.”);
});
});
</script>

And, here’s the modified version of the previous example in which the alert( ) statement is placed
inside a callback function for the slideToggle( ) method. Now, the alert message will be displayed
once the slide toggle effect has completed.

<script>
$(document).ready(function( ){
$(“.btn1”).click(function( ){
$(“p”).slideToggle(1000, function( ){
alert(“Hide( ) method is finished!”);
});
});
});
</script>

Q3. Explain in detail about JQuery selectors with examples.


JQuery selectors: JQuery selectors are used to select and manipulate HTML element(s).
HTML elements can be selected based on their name, id, classes, types, attributes, values of
attributes and much more.
All selectors in JQuery start with the dollar sign and parentheses: $( ). It supports existing
CSS Selectors as well as non-standard selectors.
The factory function $( ) is a synonym of JQuery( ) function. So in case of using any other JavaScript
library where $ sign is conflicting with something else then $ sign can be replaced by JQuery name
and JQuery( ) function can be used instead of $( ).
Types of JQuery Selectors:
1. CSS Element Selector
2. CSS Element ID Selector
3. CSS Element Class Selector
4. CSS Universal Selector

5. Multiple Elements E, F, G Selector.

10
Advanced Java Script

1. CSS Element Selector:


The JQuery element selector selects elements based on the element name (tag name
available in the DOM). It is also known as “tag selector”. It is denoted by $(“tag name”)

Example:

$(“p”) selects all the elements with tag name <p> in the document.

<html>
<head>
<title> The JQuery Example</title>
<script type=“text/javascript”
src=”https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”>
</script>
<script type=”text/javascript” language=”javascript”>
$(documents).ready(function( )
{
$(“p”).css(“background-color”, “yellow”);
});
</script>
</head>
<body>
<div>
<p> This is a paragraph.</p>
<div>
</body>
</html>

Output:
This is a paragraph.

2. CSS Element ID Selector:


The JQuery element ID selector selects elements based on the id attribute of HTML tag in
the DOM.
An id must be unique within a page, so #id Selector is to be used to select a single, unique
element. It is denoted by $(“#id name”)

Example:
$(“#test”) selects all elements having (id=test> in the document.
<!DOCTYPE html>
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script>
<script>

11
Advanced Java Script

$(document).ready(function( ) {
$(“button”).click(function( ){
$(“#test”).hide( );
});
});
</script>
</head>

<body>
<h2> This is a heading</h2>
<p> This is a paragraph.</p>
<p id=“test”> This is another paragraph.</p>
<button> Click me</button>
</body>
</html>

Output: When a user clicks on a button, the element with id=“test” will be hidden
This is a heading This is a heading
This is another paragraph. This is a paragraph
Click me Click me

3. CSS Element Class Selector:


The JQuery element Class selector selects elements that match with the given class in the
DOM.
It is denoted by $(“.name of the class”)
Example:
$(“#test”) selects all elements having <class=test> in the document.

<!DOCTYPE html>
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script>

<script>

$(document).ready(function( )[
$(“button”).click(function( )[
$(“.test”).hide( );
});
});
</script>
</head>

<body>

12
Advanced Java Script

<h2 class=“test”> This is a heading </h2>


<p> This is a paragraph. </p>
<p class=“test”> This is another paragraph.</p>
<button>Click me</button>
</body>
</html>

Output: When a user clicks on a button, the element with class=“test” will be hidden
This is a heading This is a paragraph
This is another paragraph.
Click me
Click me

4. CSS Universal Selector:


The JQuery Universal selector selects all the elements available in the DOM. This selector
will select every element including head, body etc.
It is denoted by $(“*”)
Example:
<!DOCTYPE html>
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script>

<script>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“*”).hide( );
});
});
</script>
</head>

<body>
<h2>This is a heading</h2>
<p> This is a paragraph.</p>
<p> This is another paragraph.</p>
<button>Click me</button>
</body>
</html>

Output: When a user clicks on a button, all elements will be hidden including click me
This is a heading
This is another paragraph.
Click me

13
Advanced Java Script

5. Multiple Elements E, F, G Selector:


The JQuery Multiple Elements selector selects the combined results of all the specified
selectors E, F or G and produces a single result.
It is denoted by $(“E, F, G”)
Example:

<!DOCTYPE html>
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script>

<script>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“p, #test, .id”).css(“background-color”, “yellow”):
;
});
});
</script>
</head>

<body>
<h2 class=id> This is a heading </h2>
<p> This is a paragraph.</p>

<button>Click me</button>
</body>
</html>

Output: When a user clicks on a button, the selected elements will be applied yellow color
background
This is a hedaing This is a heading
This is a paragraph. This is a paragraph
This is another paragraph.
Click me
Click me

Q4. Explain JQuery DOM attributes with example each.


Get Attribute Value:
The attr( ) method sets or returns attributes and values of the selected elements.
When this method is used to return the attribute value, it returns the value of the FIRST matched
element.

14
Advanced Java Script

When this method is used to set attribute values, it sets one or more attribute/value pairs for the
set of matched elements.
Syntax:
Return the value of an attribute: $(selector).attr(attribute)
Set the attribute and value: $(selector).attr(attribute, value)
Set attribute and value using a function:$(selector).attr(attribute,function(index,currentvalue))
Set multiple attributes and values: $(selector).attr({attribute:value,attribute:value,….})

Example:
Set the width attribute of an image:
$(“button”).click(function( ){
$(“img”).attr(“width,”, “500”);
});

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”);
});
</script>
</head>
<body>
<div>
<img id=“myimg” src=“/wongpath.jpg” alt=“sample image”/>
</div>
</body>
</html>

15
Advanced Java Script

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 set src attribute of an image tag to a correct location.
<html>
<head>
<title> The title</title>
<script type=“text/javascript” src=“/jquery/jquer-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>

Q5. List out methods to manipulate JQuery DOM attributes and describe them with suitable
examples.
Methods to manipulate DOM attributes and properties:

Methods Description
attr(properties) Set a key/value object as properties to all matched elements.
attr(key, fn) Set a single property to a complete value, on all matched elements.
removeAttr(name) Remove an attribute from each of the matched elements.
hasClass(class) Returns true if the, specified class is present on at least one of the set of
matched elements.
removeClass(class Remove all or the specified class(es) form the set of matched elements.
)
toggleClass(class) Adds the specified class if it is not present, removes the specified class if it is

16
Advanced Java Script

present
html( ) Get the html contents (inner html) of the first matched element.
html(val) Set the html contents of every matched elements.
text( ) Get the combined text contents of all matched elements.
text(val) Set the text contents of all matched elements.
val( ) Get the input value of the first matched element.
val(val) Set the value attribute of every matched element if it is called on <input> but
if it is called on <select> with the passed <option> value then passed option
would be selected, if it is called on check bor or radio box then all the
matching check box and radiobox would be checked.

Examples:
(1) $(“#myID”).attr(“custom”):

It returns a value of attribute custom for the first element matching with ID myID.

(2) $(“img”).attr(“alt”, “Sample Image”):

It sets the alt attribute of all the images to a new value “sample image”.

(3) $(“input”).attr(value:“ ”, title: “please enter a value”}); :

It sets the value of all <input> elements to the empty string, as well as sets the title to the
string please enter a value.

(4) $(“a[href^=http://]”).attr(“target”, “_blank”);

It selects all links with an href attribute starting with http:// and set its target attribute to
_blank

(5) $(“a”).removeAttr(“target”) :

It removes target attribute of all the links.

(6) $(“form”).submit(function( ) {$(“.submit”, this).attr(“disabled”, “disabled”);}); :

It modifies the disabled attribute to the value “disabled” while clicking submit button.

(7) $(“p.text”).hasClass(“selected”):

It return true if last <p> tag has associated class selected.

(8) $(“p”).text( ):

Return string that contains the combined text contents of all matched <p> elements.

(9) $(“p”).text(“<i>Hello World</i>”):

17
Advanced Java Script

This would set “<i>Hello World<i>” as text content of the matching <p> elements.

(10) $(“p”).html( ):

This returns the HTML content of the all matching paragraphs.

(11) $(“div”).html(“Hello World”):

This would set the HTML content of all matching <div> to Hello World.

(12) $(“input:checkbox:checked”).val( ):

Get the first value from a set of radio buttons

(13) me=bar]:checked”).val( ):

Get the first value from a set of radio buttons

(14) $(“button”).val(“Hello”):

Get the value attribute of every matched element <button>.

(15) $(“input”).val(“on”):

This would check all the radio or check box button whose value is “on”.

(16) $(“select”).val(“Orange”, “Mango”):

This would select Orange and Mango options in a dropdown box with options Orange,
Mango and Banana.

Q6. Briefly explain about JQuery – DOM Traversing.


JQuery DOM Traversing:
JQuery traversing (“moving through”) is used to “find” (or select) HTML elements based on
their relation to other elements.
With JQuery traversing, we 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.
JQuery is a very powerful tool which provides a variety of DOM traversal methods to help us
select elements in 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.
Search Elements by Index:
The eq( ) method returns an element with a specific index number of the selected elements.

18
Advanced Java Script

The index numbers start at 0, so the first element will have the index number 0 (not 1).
Syntax
$(selector).eq(index)
Example: 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>

Filtering out Elements:


The filter(selector) method can be used to filter out all elements from the set of matched
elements that do not match the specified selector(s).

Syntax
$(selector).filter(criteria, function(index))
Example: adds color to the lists associated with middle class

19
Advanced Java Script

<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”).filter(“.middle”).addclass(“selected”);
});
</script>
<style>
.selected {color:red;}
</style>
</head>
<body>
<div>
<ul>
<li class=“top”> list item 1 </li>
<li class=“top”> list item 2 </li>
<li class=“middle”> list item 3 </li>
<li class=“middle”> list item 4 </li>
<li class=“bottom”> list item 5 </li>
<li class=“bottom”> list item 6 </li>
</ul>
</div>
</body>
</html>

Locating Descendent Elements:


The find(selector) method can be used to locate all the descendent elements of a particular
type of elements. A descendant is a child, grandchild, great – grandchild, and so on.
Syntax
$(selector).find(filter)
Example: 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>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( ){

20
Advanced Java Script

$(“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>
Q7. List out JQuery DOM Traversing Methods and describe them.
Methods used to filter out various elements from a list of DOM elements.

Selector Description
eq(index) This reduces the set of matched elements to a single element.
filter(selector) This removes all the elements from the set of matched elements that do not
match the specified selector(s).
filter(fn) This removes all the elements from the set of matched elements that do not
match the specified functions.
is(selector) It checks the current selection against an expression and returns true, if at
least one element of the selection fits the given selector.
map(callback) It translate a set of elements in the JQuery object onto another set of values in
a JQuery array(which may, or may not contain elements).
not (selector) This removes the elements matching the specified selector from the set of
matched elements.
slice(start, [end]) It selects a subset of the matched elements.

Methods used to locate various elements in a DOM:

Selector Description
add(selector) Adds more elements, matched by the given selector, to the set of matched
elements.
andSelf( ) Add the previous selection to the current selection.
children ([selector]) Get a set of elements containing all of the unique immediate children of
each of the matched set of elements.

21
Advanced Java Script

closest(selector) Get a set of elements containing the closest parent element that matches the
specified selector, the starting element included.
contents( ) Find all the child nodes inside the matched elements (including text nodes),
or the content document, if the element is an iframe.
end( ) Revert the most recent ‘destructive’ operation, changing the set of matched
elements to its previous state.
find (selector) Searches for descendent elements that match the specifies selectors.
next( [selector]) Get a set of elements containing the unique next siblings of each of the given
set of elements.
nextAll( [selector]) Find all sibling elements after the current element.
offsetParent( ) Returns a JQuery collection with the positioned parent of the first matched
element.
parent( [selector]) Get the direct parent of an element. If called on a set of elements, parent
returns a set of their unique direct parent elements.
parents( [selector]) Get a set of elements containing the unique ancestors of the matched set of
elements (except for the root element).
prev( [selector]) Get a set of elements containing the unique previous siblings of each of the
matched set of elements.
prevAll( [selector]) Find all sibling elements in front of the current element.
siblings( [selector]) Get a set of elements containing all of the unique siblings of each of the
matched set of elements.

SHORT ANSWER QUESTIONS

Q.1. Explain the following in JQuery.


(a) String (b) Numbers (c) Boolean (d) Objects (e) Arrays
JQuery is a framework built using javascript capabilities. So all the functions and other
capabilities available in javascript can be used in JQuery.
(a) 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:
1. “This is JavaScript String”
2. ‘This is JavaScript String’
3. ‘This is “really” a JavaScript String’
4. “This is ‘really’ a Javascript String”
(b) 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:
1. 5350

22
Advanced Java Script

2. 120.27
3. 0.26
(c) Boolean: A Boolean in JavaScript can be either true or false. If a number is zero, it defaults to
false. If an empty string defaults to false:
Following are the valid examples of a JavaScript Boolean:
1. true //true
2. false //false
3. 0 //false
4. 1 //true
5. “ ” //false
6. “hello” //true
(d) Objects: An object can be created using the object literal as follows:
var emp={
name: “zara”,
age: 10
};

Write and read properties of an object can be done using he dot notations as follows:
//getting object properties
Emp.name //zara
Emp.age //10

//setting object properties


Emp.name=“Daisy” //Daisy
Emp.age=20 //20
(e) Arrays: Arrays can be defined 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.2. What are the advantages and disadvantages of an JQuery?


Advantages:

23
Advanced Java Script

1. Ease of use: It is easy to use compared to standard javascript and other javascript
libraries. Apart from simple syntax, it also requires much less lines of code to achieve
the same feature in comparison.
2. Large library: JQuery enables you to perform hordes of functions in comparison to
other JavaScript libraries.
3. Strong opensource community. (Several JQuery plugins available): JQuery, while
relatively new, has a following that religiously devote their time to develop and enhance
the functionality of JQuery. Thus there are hundreds of prewritten plugins available for
download to instantly speed up your development process. Another advantage behind
this is the efficiency and security of the script.
4. Great documentation and tutorials: The JQuery website has a comprehensive
documentation and tutorials to get even an absolute beginner in programming to get
the ball rolling with this library.
5. Ajax support: JQuery lets you develop Ajax templates with ease, Ajax enables a sleeker
interface where action can be performed on pages without requiring the entire page to
be reloaded. A pretty but simple example of this can be seen above the fold on how to
refinance your mortgage.net.
Disadvantages:

1. Functionality maybe limited: While JQuery has an impressive library in terms of


quantity, depending on how much customization you require on your website,
functionality maybe limited thus using raw javascript maybe inevitable in some cases.
2. JQuery javascript file required: The JQuery javascript file is required to run JQuery
commands, while the size of this file is relatively small (25-100KB depending on server),
it is still a strain on the client computer and may be your web server as well if you
intend to host the JQuery script on your own web server.

24
Advanced Java Script

Unit – II
JQuery – CSS Methods
Essay Questions
Q.1. How to apply and return CSS properties using JQuery CSS Methods. Explain with an example.
JQuery CSS Methods:
JQuery CSS method css( ) is used to apply one or more(multiple) CSS properties on DOM elements.
It is also used to return style properties for the selected elements.
(i) Applying a single CSS property: JQuery CSS method can apply single CSS property on the
selected element as follows:
selector.css(“PropertyName”, “PropertyValue”);
Here property name can be a javascript string, and based on its value, property value could
be string or integer.
Example:
$(“p”).css(“background-color”, “yellow”); will apply background color value yellow for all the
elements with tag name <p> in the document.

<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( )
{
$(“p”).css(“background-color”, “yellow”):
});
</script>
</head>
<body>
<div>
<p> This is a Paragraph. </p>
</div>
</body>
</html>
Output:
This is a Paragraph

25
Advanced Java Script

(ii) Applying multiple CSS properties: JQuery CSS method can apply multiple CSS properties on
the selected element as follows:
selector.css({“PropertyName”, “PropertyValue”, “PropertyName”, “PropertyValue”, …..});
Example:
$(“p”).css({“background-color”: “yellow”, “color”:“red” }); will apply background color
value yellow and font color value red for all the elements with tag name <p> in the document.

<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( )
{
$(“p”).css({“background-color”:“yellow”, “color”: “red”});
});
</script>
</head>
<body>
<div>
<p> This is a Paragraph. </p>
</div>
</body>
</html>
Output:
This is a Paragraph

(iii) Return CSS properties: JQuery CSS method can also return CSS properties applied on the
selected element as follows:
alert(selector.css(“PropertyName”));
Example:
alert($(“p”).css(“background-color”)); will return background color value yellow
RGB(255, 255, 0) for the first element with tag name <p> in the document.
<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>

26
Advanced Java Script

<script type=“text/javascript” language=“javascript”>


$(document).ready(function( ){
{
Alert($(“p”).css(“background-color”)):
});
</script>
</head>
<body>
<div>
<p style=“background-color:yellow”> This is a Paragraph. </p>
</div>
</body>
</html>
Output:

Q.2. List out JQuery dimension methods and display all the dimensions using related methods.
JQuery Dimension Methods:
JQuery CSS methods that are used for working with dimensions are called JQuery dimension
methods.

JQuery Dimension
S.No. Description
Method
1. width( ) Sets or return the width of an element (excludes padding, border and
margin).
2. height( ) Sets or returns the height of an element (excludes padding, border
and margin).
3. innerWidth( ) Returns the width of an element (includes padding).
4. innerHeight( ) Returns the height of an element (includes padding).
5. outerWidth( ) Returns the width of an element (includes padding and border).
6. outerHeight( ) Returns the height of an element (includes padding and border).
7. outerWidth(true) Returns the width of an element (includes padding, border and
margin).
8. outerHeight(true) Returns the height of an element (includes padding, border and
margin).

27
Advanced Java Script

Margin

Border

Padding

outerHeight(true)
outerHeight( )
innerHeight( )
Element

height( )
Width( )

innerWidth( )
outerWidth( )

outerWidth(true)

1. Syntax for displaying width and height of an element:


selector.width( );
selector.height( );
2. Syntax for displaying inner width and inner height of an element:
selector.innerWidth( );
selector.innerHeight( );
3. Syntax for displaying outer width and outer height of an element:
selector.outerWidth(true);
selector.outerHeight(true);
Examples:
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script>
<script>
$(document).ready(function( ){
$(“button”).click(function( ){
var txt= “ ”;
txt+=“Width of div:” + $(“#div1”).width( ) + “</br>”;
txt+= “Height of div:” + $(“#div1”).height( )+ “</br>”;
txt+=“Inner Width of div:” + $(“#div1”).innerWidth( ) + “</br>”;
txt+= “Inner Height of div:” + $(“#div1”).innerHeight( )+ “</br>”;
txt+=“Outer Width of div (margin included):” + $(“#div1”).outerWidth( ) + “</br>”;
txt+=“Outer Height of div (margin included):” + $(“#div1”).outerHeight( ) + “</br>”;
txt+=“Outer Width of div (margin included):” + $(“#div1”).outerWidth(true) + “</br>”;
txt+=“Outer Height of div (margin included):” + $(“#div1”).outerHeight(true) + “</br>”;
$(“#div1”).html(txt);

28
Advanced Java Script

});
});
</script>
<style>
#div1 {
height: 150px;
width: 300px;
padding: 10px;
margin: 3px
border: 1px solid blue;
background-color: lightblue;
}
</style>
</head>
<body>
<div id=“div1”> </div>
<br>
<button>Display dimensions of div</button>
</body>
</html>
Output:
Width of div: 300
Height of div: 150
Inner width of div: 320
Inner height of div: 170
Outer width of div (margin included): 322
Outer height of div (margin included): 172
Outer width of div (margin included):328
Outer height of div (margin included): 178

Display
Display dimensions
dimensions of
of div
div Display
Display dimensions
dimensions of
of div
div

Q.3. How to set and return element width in JQuery. Explain with an example.
Margin

Border

Padding

Element

Width( )

29
Advanced Java Script

(i) Setting Element Width:


When this method is used to set element width, it sets the width of ALL matched elements
using the syntax
selector.width(value);
Example: This will sets the width using different units.
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function( ){
$(“#btn1”).click(function( ) {
$(“div”).width(500);
});
$(“#btn2”).click(function( ) {
$(“div”).width(“10em”);
});
$(“#btn3”).click(function( ) {
$(“div”).width(“300pt”);
});
$(“#btn4”).click(function( ) {
$(“div”).width(function(n, c){
return c – 200;
});
});
});
</script>
</head>
<body>
<button id=“btn1”>Set width of div to 500px</button>
<button id=“btn2”>Set width of div to 10em</button>
<button id=“btn3”>Set width of div to 300pt</button>
<button id=“btn4”>decrease width of div with 200 </button>
<p><b>Note:</b>Use “” for em, pt, etc. </p>
<div style=“height:100px; width:300px; border:1px solid blue; background-color:lightblue;”>
</div><br>
</body>
</html>

30
Advanced Java Script

Output: on clicking any of them, width will be increased.

Set
Set width
width of
of div
div to
to 500px
500px Set
Set width
width of
of div
div to
to 10em
10em Set
Set width
width of
of div
div to
to 300pt
300pt Decrease
Decrease width
width of
of div
div with
with 200
200

Note: Use “” for em, pt, etc.

(ii) Return Element Width:


When this method is used to return element width, it returns the width of FIRST matched
elements using the syntax.

alert(selector.width( ));
Example:
This will returns the width of selected element in an alert box and also returns the width of current
window and current document.

<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function( ){
$(“button”).click(function( ) {
alert(“Width of div:” + $(“div”).width( ));
$(“#span1”).text($(window).width( ) );
$(“#span2”).text($(document).width( ) );
});
});
</script>
</head>
<body>
<p>The width of this window is <span id= “span1”> unknown</span>px.</p>
<p>The width of this document is <span id= “span2”> unknown</span>px.</p>
<button> Display the width of div, window and document </button>
<div style= “height:100px; width:300px; border:1px solid blue; background-color: lightblue;”>
</div><br>
</body>
</html>

31
Advanced Java Script

Output: after clicking ok in alert box width will be displayed.

Q.4. How to set and return element height in JQuery. Explain with an example.
Margin

Border

Padding

Element

height( )

(i) Setting Element height: When this method is used to set element height, it sets the height of
ALL matched elements using the syntax.
Selector.height(value);

Example: This will sets the height using different units.


<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function( ){
$(“#btn1”).click(function( ) {
$(“div”).height(500);
});
$(“#btn2”).click(function( ) {
$(“div”).height (“10em”);
});
$(“#btn3”).click(function( ) {
$(“div”).height (“300pt”);
});
$(“#btn4”).click(function( ) {

32
Advanced Java Script

$(“div”).height (function(n, c){


return c + 200;
});
});
});
</script>
</head>
<body>
<button id=“btn1”>Set height of div to 500px</button>
<button id=“btn2”>Set height of div to 10em</button>
<button id=“btn3”>Set height of div to 300pt</button>
<button id=“btn4”>increase height of div with 200 </button>
<p><b>Note:</b>Use “” for em, pt, etc. </p>
<div style=“height:100px; width:300px; border:1px solid blue; background-color:lightblue;”>
</div><br>
</body>
</html>

Output: on clicking any of them, height will be increased.

Set
Set height
height of
of div
div to
to 500px
500px Set height of
Set height of div
div to
to 10em
10em Set height of
Set height of div
div to
to 300pt
300pt increase height of
increase height of div
div with
with 200
200

Note: Use “” for em, pt, etc.

(ii) Return Element Height: When this method is used to return element height, it returns the
height of FIRST matched elements using the syntax.

alert(selector.height( ));

Example: This will returns the height of selected element in an alert box and also returns the
height of current window and current document.

<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function( ){

33
Advanced Java Script

$(“button”).click(function( ) {
alert(“height of div:” + $(“div”).height ( ));
$(“#span1”).text($(window).height ( ) );
$(“#span2”).text($(document).height( ) );
});
});
</script>
</head>
<body>
<p>The height of this window is <span id= “span1”> unknown</span>px.</p>
<p>The height of this document is <span id= “span2”> unknown</span>px.</p>
<button> Display the height of div, window and document </button>
<div style= “height:100px; width:300px; border:1px solid blue; background-color: lightblue;”>
</div><br>
</body>
</html>

Output: after clicking ok in alert box height will be displayed.

Q.5. Explain in detail about DOM Content manipulation in JQuery with an example.
Content Manipulation: DOM elements content can be manipulated using
1. html( ); 2. text( )
1. html() method: The html() method sets or returns the content (inner HTML – text + HTML
markup) of the selected elements.
(i) Set Content: When this method is used to set content, it overwrites the content of ALL matched
elements using the syntax
Selector.html(“content”);
Example: $(“p”).html(“<b> Content modified</b>”); will change the content of all the elements
with tag name <p> and in the document bolds it.

<html>
<head>
<title> The JQuery Example </title>

34
Advanced Java Script

<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“p”).html(“<b>Content modified</b>”):
});
});
</script>
</head>
<body>
<p>Given content.</p>
<button> Change content of all p elements</button>
</body>
</html>
Output:
Given content. Content modified
Change
Change content
content of
of all
all p
p elements
elements Change
Change content
content of
of all
all p
p elements
elements

(ii) Return Content: When this method is used to return content, it returns the content of FIRST
matched elements using the syntax
alert(selector.html( ) );
Example: alert($(“p”).html( )); will return the content of all the elements with tag name<p> in the
document.

<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( ){
$(“button”).click(function( ){
alert($(“p”).html( )):
});
});
</script>
</head>

35
Advanced Java Script

<body>
<p>content<b>displayed</b> in alert box.</p>
<button>Return content of all p elements</button>
</body>
</html>
Output:

2. text( ) method: The text( ) method sets or returns the text content of the selected elements.
(i) Set Content: When this method is used to set content, it overwrites the content of ALL matched
elements using the syntax.
selector.text(“content”);
Example: $(“p”).text(“<b>Content modified</b>”); will change the content of all the elements
with tag name <p> in the document but bolding will not be applied.

<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( )
{
Alert($(“p”).css(“background-color”)):
});
</script>
</head>
<body>
<p>Given content.</p>
<button> Change content of all p elements</button>
</body>
</html>
Output:
Given content. Content modified
Change
Change content
content of
of all
all p
p elements
elements Change
Change content
content of
of all
all p
p elements
elements

36
Advanced Java Script

(ii) Return Content: When this method is used to return content, it returns the content of
FIRST matched elements using the syntax
selector.text( );
Example: alert($(“p”).text( )); will return the content of all the elements with tag name <p> in the
document but discards <b> and </b> elements in <p>.

<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( ){
$(“button”).click(function( ){
alert($(“p”).html( ));
});
});
</script>
</head>
<body>
<p>content<b>displayed</b> in alert box</p>
<button>Return content of all p elements</button>
</body>
</html>

Output:
Content displayed in alert box. X

Return content of all p elements This pages says:


Content displayed in alert box.
OK

Q.6. Explain in detail about DOM Element Replacement in JQuery with an example.
Replacing DOM Element: DOM elements content can be manipulated using
1. replaceAll( )
2. replaceWith( )
1. replaceAll( ) method: The replaceAll( ) method replaces selected elements with new
HTML elements using the syntax

37
Advanced Java Script

$(content).replaceAll(“selector”);

Example: $(“<h2>Hello world!</h2>”).replaceAll(“p”); will replace the content of all elements


with tag name <p> in the document.

<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“<h2>Hello world!</h2>”).replaceAll(“p”);
});
});
</script>
</head>
<body>
<p>content in first paragraph.</p>
<p>content in second paragraph.</p>
<button>replace content of all p element</button>
</body>
</html>

Output:
Hello world!
content in first paragraph
content in second paragraph Hello world!

replace content of all p element


replace content of all p element

2. replaceWith( ) method: The replaceWith( ) method replaces selected elements with new
content using the syntax
selector.replaceWith(“content”);
Example: $(“p:first”).replaceWith(“<h1>Hello world!</h1>”); will replace the content of first
element with tag name <p> in the document.

<html>
<head>

38
Advanced Java Script

<title> The JQuery Example </title>


<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“p:first”).replaceWith(“<h1>Hello world!</h1>”);
});
});
</script>
</head>
<body>
<p>content in first paragraph.</p>
<p>content in second paragraph.</p>
<button>replace content of first p element</button>
</body>
</html>

Output:
content in first paragraph
Hello world!
content in second paragraph
Content in second paragraph
replace content of first p elements

replace content of first p elements

Q.7. Explain how to remove DOM Element in JQuery with an example.


Removing DOM Element: DOM elements can be removed using
1. remove( )

2. detach( )

3. empty( )
1. remove( ) method: The remove( ) method removes the selected elements, including all
text and child nodes. This method also removes data and events of the selected elements.

selector.remove( );

Example: $(this).remove( ); will remove the selected one.

39
Advanced Java Script

<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>

<script type=“text/javascript” language=“javascript”>


$(document).ready(function( ){
$(“div”).click(function( ) {
$(this).remove( );
});
});
</script>

<style> div{margin:10px;padding:12px;border:2px solid#666; width:60px;} </style>


</head>

<body>
<p>Click on any square below:</p>
<span id= “result”></span>

<div style= “background-color:blue;”>1</div>


<div style= “background-color:green;”>2</div>
<div style= “background-color:red;”>3</div>
</body>
</html>

Output:
Click on any square below: Click on any square below: Click on any square below: Click on any square below:

2. detach( ) method: The detach( ) method removes the selected elements, including all text
and child nodes. This method keeps data and events of the selected elements.
selector.detach( );
Example: $(this).detach( ); will remove the selected one.

<html>

40
Advanced Java Script

<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( ) {
$(“div”).click(function( ) {
$(this).detach( );
});
});
</script>

<style> div{margin:10px;padding:12px;border:2px solid#666; width:60px;} </style>


</head>

<body>
<p>Click on any square below:</p>
<span id= “result”></span>

<div style= “background-color:blue;”>1</div>


<div style= “background-color:green;”>2</div>
<div style= “background-color:red;”>3</div>
</body>
</html>

Output:
Click on any square below: Click on any square below: Click on any square below: Click on any square below:

3. empty( ) method: The empty( ) method removes only the content from the selected
elements.
selector.empty( );
Example: $(this).empty( ); will remove the content of selected one but background remains same.

<html>
<head>
<title> The JQuery Example </title>

41
Advanced Java Script

<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>

<script type=“text/javascript” language=“javascript”>


$(document).ready(function( ){
$(“div”).click(function( ) {
$(this).empty( );
});
});
</script>

<style> div{margin:10px;padding:12px;border:2px solid#666; width:60px;} </style>


</head>

<body>
<p>Click on any square below:</p>
<span id= “result”></span>

<div style= “background-color:blue;”>1</div>


<div style= “background-color:green;”>2</div>
<div style= “background-color:red;”>3</div>
</body>
</html>

Output:
Click on any square below: Click on any square below: Click on any square below: Click on any square below:

Q.8. Explain how to insert DOM Element in JQuery with an example.


Inserting DOM Element: DOM elements can be inserted using–
1. after( )

2. before( )
3. append( )
4. appendTo( )
5. prepend( )
6. prependTo( )
7. insertAfter( )

42
Advanced Java Script

8. insertBefore( )

1. after( ) method: The after( ) method inserts specified content after the selected elements.
selector.after(content);
Example: $(“p”).after(“<p>Hi students</p>”); will insert content after <p> content in <body>
section

<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”> </script>
<script>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“p”).after(“<p>Hi students</p>”);
});
});
</script>
</head>

<body>
<button>Insert content after each p element</button>
<p> How are you </p>
</body>
</html>

Output:
Insert
Insert content
content after
after each
each p
p element
element Insert
Insert content
content after
after each
each p
p element
element

How are you How are you

Hi students

2. before( ) method: The before( ) method inserts specified content after the selected
elements.
selector.before(content);

Example: $(“p”).before(“<p>Hi students</p>”); will insert content after <p> content in <body>
section

<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”> </script>

43
Advanced Java Script

<script>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“p”).before(“<p>Hi students</p>”);
});
});
</script>
</head>
<body>
<button>Insert content before each p element</button>
<p> How are you </p>
</body>
</html>

Output:
Insert
Insert content
content before
before each
each p
p element
element Insert
Insert content
content before
before each
each p
p element
element

How are you Hi students

How are you

3. append( ) method: The append( ) method inserts specified content at the end of the
selected elements.
selector.append(content)
Example: $(“p”).append(“?”); will insert? at the end of <p> content in <body> section.

<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”> </script>
<script>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“p”).append(“?”);
});
});
</script>
</head>
<body>
<button>Insert content at the end</button>

44
Advanced Java Script

<p> How are you </p>


</body>
</html>

45
Advanced Java Script

Output:

Insert content at the end Insert content at the end

How are you How are you?

4. appendTo( ) method: The appendTo( ) method inserts HTML elements at the end of the
selected elements.

$(content).appendTo(selector);
Example: $(“<li>?</li>”).appendTo(“ol”); will append? to <ol> content in <body> section

<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”> </script>
<script>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“<li>?</li>”).appendTo(“ol”);
});
});
</script>
</head>
<body>
<ol>
<li> List item 1</li>
<li> List item 2</li>
<li> List item 3</li>
</ol>
<button>Append content at the end of ol element</button>
</body>
</html>

Output:

1. List item 1 1. List item 1


2. List item 2 2. List item 2
3. List item 3 3. List item 3

Append content at the Append content at the


end of the element end of the element

46
Advanced Java Script

5. prepend( ) method: The prepend( ) method inserts specified content at the beginning of
the selected elements.
selector.prepend(content);
Example: $(“p”).prepend(“Hi,”); will insert ? ? to <ol> content in <body> section

<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”> </script>
<script>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“p”).prepend(“Hi,”);
});
});
</script>
</head>
<body>
<button>Insert content at the beginning </button>
<p> How are you </p>
</body>
</html>

Output:

Insert content at the beginning Insert content at the beginning

How are you Hi, How are you

6. prependTo( ) method: The prependTo( ) method inserts HTML elements at the


beginning of the selected elements.
$(content).prependTo(selector);
Example: $(“<li>?</li>”).prependTo(“ol”); will append? to <ol> content in <body> section

<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”> </script>
<script>
$(document).ready(function( ){

47
Advanced Java Script

$(“button”).click(function( ){
$(“<li>?</li>”).prependTo(“ol”);
});
});
</script>
</head>
<body>
<ol>
<li> List item 1</li>
<li> List item 2</li>
<li> List item 3</li>
</ol>
<button>Append content at the beginning of ol element</button>
</body>
</html>

Output:

1. List item 1 1. ?
2. List item 2 2. List item 1
3. List item 3 3. List item 2
4. List item 3
Append content at the Append content at the
beginning of ol element beginning of ol element

7. insertAfter( ) method: The insertAfter( ) method inserts HTML elements after the selected
elements.
$(content).insertAfter(selector);

Example: $(“<li>?</li>”).insertAfter(“ol”); will append? after <ol> tag in <body> section

<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”> </script>
<script>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“<li>?</li>”).insertAfter(“ol”);
});

48
Advanced Java Script

});
</script>
</head>
<body>
<ol>
<li> List item 1</li>
<li> List item 2</li>
<li> List item 3</li>
</ol>
<button>Append content after ol element</button>
</body>
</html>

Output:

1. List item 1 1. List item 1


2. List item 2 2. List item 2
3. List item 3 3. List item 3
Append content after ol Append content after ol
element element

8. insertBefore( ) method: The insertBefore( ) method inserts HTML elements before the
selected elements.
$(content).insertBefore(selector);

Example: $(“<li>?</li>”).insertBefore(“ol”); will append? before <ol> tag in <body> section

<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”> </script>
<script>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“<li>?</li>”).insertBefore(“ol”);
});
});
</script>
</head>
<body>

49
Advanced Java Script

<ol>
<li> List item 1</li>
<li> List item 2</li>
<li> List item 3</li>
</ol>
<button>Append content before ol element</button>
</body>
</html>

Output:

1. List item 1 ?
2. List item 2 1. List item 1
3. List item 3 2. List item 2
3. List item 3
Append content before ol element
Append content before ol element

Q.9. List out various types of DOM events in JQuery and describe them.
Types of events: 1) Mouse Events, 2) Keyboard Events, 3) Form Events,
4) Document/Window Events.

Mouse Events Description


1 click Occurs when a mouse click.
2 dbclick Occurs when a mouse double – click.
3 mouseenter Occurs when mouse enters in an element region.
4 mouseleave Occurs when mouse leaves an element region.
5 mouseup Occurs when mouse button is released.
6 mousedown Occurs when mouse button is pressed.
7 mousemove Occurs when mouse pointer moves.
8 mouseout Occurs when mouse pointer moves out of an element.
9 mouseover Occurs when mouse pointer moves over an element.
Keyboard Events Description
1 keypress Occurs when key is pressed and released.
2 keyup Occurs when key is released.
3 keydown Occurs when key is pressed.
Form Events Description
1 submit Occurs when form is submitted.
2 change Occurs when the element changes.
3 focus Occurs when the element gets focus.
4 blur Occurs when the element loses focus.

50
Advanced Java Script

Document/Window Events Description


1 load Occurs when document is loaded.
2 unload Occurs when documents is unloaded.
3 resize Occurs when window is resized.
4 scroll Occurs when window is scrolled.
5 error Occurs when there is an error in loading or unloading etc.

Q.10. How to establish event handlers on DOM elements in JQuery. Explain with an example.
Binding Event handlers: The bind( ) method attaches one or more event handlers for selected
elements, and specifies a function to run when the event occurs.
(i) Attaching a single event:
selector.bind(event, data, function, map);
Example: $(“p”).click( ); assigns a bind event to all elements with tag name <p> in the document.
Now, a function is to be passed to the event to define what should happen when the event fires.
$(“p”).click(function( ) {
//action goes here!!
});

Here $(“p”).bind(“click”, function( ){}); attaches click event to the elements with tag name <p> in
the document.

<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>

<script type=“text/javascript” language=“javascript”>


$(document).ready(function( )
{
$(“p”).bind(“click”, function( )(alert(“The paragraph was clicked.”);} );
});
</script>
</head>
<body>
<p> click me</p>
</body>
</html>

51
Advanced Java Script

Output:
click me X

This page says:


The paragraph was clicked.
OK

(ii) Attaching multiple events: Multiple event values are separated by space.
selector.bind(“event event”, data, function, map);
Example: Here $(“p”).bind(“mouseover mouseout”, function( ){}); attaches multiple
(mouseover, mouseout) event to the elements with tag name <p> in the document.

<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>

<script type=“text/javascript” language=“javascript”>


$(document).ready(function( ) {
$(“p”).bind(“mouseover mouseout”, function( ){
$(“p”).toggleClass(“intro”);
});
});
</script>
<style>
.intro {
font-size: 150%
color: red;
}
</style>
</head>
<body>
<p>place mouse here and move out</p>
</body>
</html>

Output: When placed mouse on the paragraph, it changes to red color, when removed changes to
black.
Place mouse here and move out Place mouse here and move out

52
Advanced Java Script

(iii) Using event map while attaching events:


selector.bind(event, data, function, map);
Specifies an event map ({event:function, event:function,……..}) containing one or more events to
attach to the elements, and functions to run when the event occurs.

Example: $(“button”).bind({…}); attaches events click, mouseover, mouseout using event map to
the selected elements in the document.

<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>

<script type=“text/javascript” language=“javascript”>


$(document).ready(function() {
$(“button”).bind({
click:function(){$(“p”).slideToggle();}, mouseover:function() {$(“body”).css(“background-color”,
“yellow”);}, mouseout:function() {$(“body”).css(“background-color”, “blue”);}
});
});
</script>
</head>
<body>
<p>click me.</p>
<button>Click me!</button>
</body>
</html>

Output: when placed mouse on the click me, background changes to red color, when removed
changes to blue and when “click me!” button is clicked, it hides the statement click me and when
again clicked it displays the statement.

53
Advanced Java Script

(iv) Using data while attaching events: This field is optional and specifies additional data to pass
along to the function.
selector.bind(event, data, function, map);
Example: $(“button”).bind({…..}); attaches click event to the elements with tag name <p> in the
document and additional data {msg: “You just clicked me!”}

<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>

<script type=“text/javascript” language=“javascript”>


function handlerName(e){
alert(e.data.msg);
}
$(document).ready(function(){
$(“p”).bind(“click”, {msg: “You just clicked me!”}, handlerName);
});
</script>
</head>
<body>
<p> click me.</p>
</body>
</html>

Output:

Q.11. How to remove event handlers that are established on DOM elements in JQuery. Explain with

an example.
Unbinding Event handlers: The unbind() method removes event handlers from selected elements.
This method can remove all or selected event handlers, or stop specified functions from running
when the event occurs.

54
Advanced Java Script

This method can also unbind event handlers using an event object. This is used to unbind an event
from within itself (like removing an event handler after the event has been triggered a certain
number of times).
Note: If no parameters are specified, the unbind() method will remove ALL event handlers from the
specified element.
(i) Removing event handler:
selector.unbind(event, function, eventobj);
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).unbind(); removes the click event on elements with tag name <p>.

<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>

<script type=“text/javascript” language=“javascript”>


$(document).ready(function()
{
$(“p”).click(function(){
$(this).slideToggle();
});
$(“button”).click(function(){
$(“p”).unbind();
});
});
</script>
</head>
<body>
<p> click me</p>
<button>Click me! To remove all event handlers for all p elements</button>
</body>
</html>

Output: in first case on clicking “click me.” it will be hided, but in second case on clicking click me!
to remove button, toggle effect will be removed and even on clicking “click me.” it will not
hide.

55
Advanced Java Script

(ii) Removing a specific function: unbind a specific function from a specified event for an
element.
selector.unbind(event, function, eventobj);
Example: Here $(“p”).unbind(“click”, alertMe); removes alertMe function specified along with
click event to the elements with tag name <p> in the document.

<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script>
function alertMe() {
alert(“Hello World!”);
}
$(document).ready(function(){
$(“p”).click(alertMe);
$(“button”).click(function(){
$(“p”).unbind(“click”, alertMe);
});
});
</script>
</head>
<body>
<p> This is a paragraph.</p>
<p> This is another paragraph.</p>
<p>Click any p element to trigger an alert box.</p>
<button>Remove the alert box function from the click event for the p elements</button>
</body>
</html>

Output: in first case, on clicking any of 3 statements, alert box is displayed, but in second case on
clicking remove the alert box button, alertbox effect-on click event will be removed and even on
clicking the statements it will not display alert box.

56
Advanced Java Script

(iii) Unbinding an event handler using an event object: Specifies an event object to remove.
selector.unbind(event, function, eventobj);
Example: $(this).unbind(event); removes event function specified along with click event to the
elements with tag name <p> in the document when x>=2.

<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”> </script>
<script>
$(document).ready(function(){
var x=0;
$(“p”).click(function(event){
$(“p”).animate({fontSize:”+=5px”});
x++;
if(x>=2){
$(this).unbind(event);
}
});
});
</script>
</head>
<body>
<p style= “font-size:20px;”>Click this p element to increase its size.</p><br>
<p style= “font-size:20px;”>The size can only be increased 2 times.</p>
</body>
</html>

Output: after clicking 2 times, the statements will not increase their size.

Click this p element to increase its size. Click this p element to increase its size.
The size can only be increased 2 times.

Q.12. Explain how to hide and show the elements in JQuery with an example.

57
Advanced Java Script

(i) hide() and show(): hide() is similar to the CSS property “display:none” and hidden elements
will not be displayed at all (no longer affects the layout of the page).
The hide() method hides the selected elements using the syntax
selector.hide(speed, easing, callback);
The show() method shows the hidden, selected elements using the syntax
selector.show(speed, easing, callback);
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).hide(); hides the elements with tag name <p> on clicking Hide button.
$(“p”).show(); shows all the hidden elements with tag name <p> on clicking Show
button.

<html>
<head>
<title>The JQuery Example</title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).hide();
});
$(“.btn2”).click(function(){
$(“p”).show();
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>Hide</button>
<button class=“btn2”>Show</button>
</body>
</html>

Output:

This is a paragraph.
Hide Show

58
Advanced Java Script

(ii) hide() and show() using speed parameter: It is optional and it specifies the speed of the hide
effect. Default value is 400 milliseconds
Possible values are
(a) milliseconds; (b) “slow”; (c) “fast”.
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).hide(1000); hides the elements with tag name <p> in 1000 milliseconds on
clicking Hide button.
$(“p”).show(1000); shows all the hidden elements with tag name <p> in 1000
milliseconds on clicking Show button.

<html>
<head>
<title>The JQuery Example</title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).hide(1000);
});
$(“.btn2”).click(function(){
$(“p”).show(1000);
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>Hide</button>
<button class=“btn2”>Show</button>
</body>
</html>

(iii) hide() and show() using callback parameter: It is optional and it specifies a function that is
to be executed after the hide() method is completed.

59
Advanced Java Script

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, a callback function
is created.
A callback function is executed after the current effect is finished.
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).hide(1000, function(){}); hides the elements with tag name <p> in 1000
milliseconds on clicking Hide button and after hide effect is completed alert msg occurs.
$(“p”).show(1000, function(){}); shows all the hidden elements with tag name <p> in
1000 milliseconds on clicking Show button and after show effect is completed alert msg
occurs.

<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).hide(1000, function(){
alert(“Hide() method is finished!”);
});
$(“.btn2”).click(function(){
$(“p”).show(1000, function(){
alert(“Show() method is finished!”);
});
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>Hide</button>
<button class=“btn2”>Show</button>
</body>
</html>

Output:

60
Advanced Java Script

(iv) hide() and show() using easing parameter: It is optional and it specifies the speed of the
element in different points of the animation. Default value is “swing”.
Possible values are : (a) “swing”; (b) “linear”
Toggle between hide() and show(): The toggle() method toggles between hide() and show() for
the selected elements.
This method checks the selected elements for visibility. Shows if an element is hidden and hides if
an element is visible this creates a toggle effect.
The toggle() method toggles using the syntax
selector.toggle(speed, easing, callback);
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).hide(); hides the elements with tag name <p> on clicking Hide button.
$(“p”).show(); shows all the hidden elements with tag name <p> on clicking Show button.
Whereas $(“p”).toggle(1000, function(){}); shows all the elements when hidden and hides when
they are visible on clicking toggle button and after toggle effect is completed alert msg occurs.

<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).toggle(1000, function(){
alert(“Toggle() method is finished!”);
});
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>

61
Advanced Java Script

<button class=“btn1”>Toggle to hide and show</button>


</body>
</html>

Output:

Q.13. Explain how to apply slide effect for the elements in JQuery with an example.
Sliding effect: JQuery slide methods used to create sliding effect on elements are (1) slideUp(),
(2) slideDown(), (3) slideToggle().
The slideUp() method slides-up(hides) the selected elements using the syntax
selector.slideup(speed, easing, callback);
The slideDown() method slides-down (shows) the selected elements using the syntax
Selector.slideDown(speed, easing, callback);
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).slideUp(); hides the elements with tag name <p> on clicking slideUp button.
$(“p”).slideDown(); shows all the hidden elements with tag name <p> on clicking slideDown button.

<html>
<head>
<title>The JQuery Example</title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).slideUp();
});

62
Advanced Java Script

$(“.btn2”).click(function(){
$(“p”).slideDown();
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>Slide up</button>
<button class=“btn2”>Slide down</button>
</body>
</html>

This will produce the result

(i) slideUp() and slideDown() using speed parameter: It is optional and it specifies the speed of
the slide effect. Default value is 400 milliseconds
Possible values are (a) milliseconds; (2) “slow”; (3) “fast”.
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).slideUp(1000); hides the elements with tag name <p> in 1000 milliseconds on
clicking SlideUp button.
$(“p”).slideDown(1000); shows all the hidden elements with tag name <p> in 1000
milliseconds on clicking SlideDown button.

<html>
<head>
<title>The JQuery Example</title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).slideUp(1000);
});
$(“.btn2”).click(function(){
$(“p”).slideDown(1000);
});
});

63
Advanced Java Script

</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>Slide up</button>
<button class=“btn2”>Slide down</button>
</body>
</html>

This will produce the result

(ii) slideUp() and slideDown() using callback parameter: It is optional and it specifies a
function that is to be executed after the slideUp() is completed or slideDown() method is
completed.
JavaScript statements are executed line by line. However, with effects, the next line of code can be
run event though the effect is not finished. This can create errors. To prevent this, a callback
function is created.
A callback function is executed after the current effect is finished.

Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).slideUp(1000, function(){}); hides the elements with tag name <p> in 1000
milliseconds on clicking Hide button and after slideup effect is completed alert msg
occurs.
$(“p”).slideDown(1000, function(){}); shows all the hidden elements with tag name
<p> in 1000 milliseconds on clicking Show button and after slidedown effect is
completed alert msg occurs.

<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).slideUp(1000, function(){
alert(“SlideUp() method is finished!”);
});
});
$(“.btn2”).click(function(){
$(“p”).slideDown(1000, function(){

64
Advanced Java Script

alert(“SlideDown() method is finished!”);


});
});

});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>Slide up</button>
<button class=“btn2”>Slide Down</button>
</body>
</html>

This will produce the result

(iii) slideToggle(); The toggle() method toggles between slideUp() and slideDown() for the
selected elements.
This method checks the selected elements for visibility. Slides down if an element is hidden and
slides up if an element is visible – this creates a toggle effect.
The toggle() method toggles using the syntax
selector.slidetoggle(speed, easing, callback);
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).slideToggle(1000, function(){}); shows all the elements when hidden and hides
when they are visible on clicking toggle button and after toggle effect is completed alert
msg occurs.

<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).slideToggle(1000, function(){
alert(“Hide() method is finished!”);
});
});

65
Advanced Java Script

});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>Toggle Up and Toggle Down</button>
</body>
</html>

Q.14. Explain how to apply fade effect for the elements in JQuery with an example.
JQuery fade methods used to fade elements in and out of visibility are
(1) fadeIn (2) fadeOut() (3) fadeToggle() (4) fadeTo()
(1) fadeIn() and fadeout(): The fadeIn() method gradually changes the opacity, for selected
elements, from hidden to visible (fading effect) using the syntax
selector.fadein(speed, easing, callback);

The fadeOut() method gradually changes the opacity, for selected elements, from visible to hidden
(fading effect) using the syntax

selector.fadeOut(speed, easing, callback);

Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).fadeIn(); hides the elements with tag name <p>.
$(“p”).fadeOut(); shows all the hidden elements with tag name <p>.

<html>
<head>
<title>The JQuery Example</title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).fadeIn();
});
$(“.btn2”).click(function(){
$(“p”).fadeOut();
});

66
Advanced Java Script

});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>fade in</button>
<button class=“btn2”>fade out</button>
</body>
</html>

This will produce the result

(i) fadeIn() and fadeOut() using speed parameter: It is optional and it specifies the speed of the
fade effect. Default value is 400 milliseconds
Possible values are (a) milliseconds; (b) “slow”; (c) “fast”.

Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).fadeIn(1000); hides the elements with tag name <p> in 1000 milliseconds.
$(“p”).fadeOut(1000); shows all the hidden elements with tag name <p> in 1000 milliseconds.

<html>
<head>
<title>The JQuery Example</title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).fadeIn(1000);
});
$(“.btn2”).click(function(){
$(“p”).fadeOut(1000);
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>

67
Advanced Java Script

<button class=“btn1”>fade in</button>


<button class=“btn2”>fade out</button>
</body>
</html>

This will produce the result

(ii) fadeIn() and fadeOut() using callback parameter: It is optional and it specifies a function
that is to be executed after the fadeIn() is completed or fadeOut() method is completed.

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, a callback function
is created.

A callback function is executed after the current effect is finished.

Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.

$(“p”).fadeIn(1000, function(){}); hides the elements with tag name <p> in 1000 milliseconds
and after fadeIn effect is completed alert msg occurs.

$(“p”).fadeOut(1000, function(){}); shows all the hidden elements with tag name <p> in 1000
milliseconds and after fadeOut effect is completed alert msg occurs.

<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).fadeIn(1000, function(){
alert(“fadeIn() method is finished!”);
});
});
$(“.btn2”).click(function(){
$(“p”).fadeOut(1000, function(){
alert(“fadeOut() method is finished!”);
});
});

});
</script>

68
Advanced Java Script

</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>fade in</button>
<button class=“btn2”>fade out</button>
</body>
</html>

This will produce the result

(2) fadeToggle(): The toggle() method toggles between fadeIn() and fadeOut() for the selected
elements.
This method checks the selected elements for visibility. If an element is faded out, fadeToggle() will
fades them in and fades out if an element is faded in – This creates a toggle effect.
The toggle() method toggles using the syntax
selector.fadetoggle(speed, easing, callback);

Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).slideToggle(1000, function(){}); shows all the elements when hidden and hides
when they are visible on clicking toggle button and after toggle effect is completed alert
msg occurs.

<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).fadeToggle(1000, function(){
alert(“Hide() method is finished!”);
});
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>Toggle In and Toggle Out</button>

69
Advanced Java Script

</body>
</html>

(3) fadeTo(): The fadeTo() method gradually changes the opacity, for selected elements, to a
specified opacity (fading effect) using the syntax.
selector.fadeto(speed, opacity, easing, callback);
Specifies the opacity to fade to. Must be a number between 0.00 and 1.00

Example:

<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).fadeTo(1000, 0.2, function(){
alert(“FadeTo() method is finished!”);
});
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>Fade to</button>
</body>
</html>

Q.15. Explain how to apply custom animations for the elements in JQuery with an example.
The JQuery animate() method is used to create custom animations.
(1) Single property is animated using the syntax $(selector).animate({params}, speed, callback);
The required params parameter defines the CSS properties to be animated.
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 animation completes.
Example

<head>

70
Advanced Java Script

<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“button”).click(function(){
$(“div”).animate({left: ‘250px’});
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the
position, remember to first set the CSS position property of the element to relative, fixed, or
absolute!</p>
<div style= “background:#98bf21;height:100px;width:100px;position:absolute;”> </div>
</body>
</html>

(2) Multiple properties can be animated at the same time:


Example
$(“button”).click(function(){
$(“div”).animate({
left: ‘250px’,
opacity: ‘0.5’,
height: ‘150px’,
width: ‘150px’
});
});

(3) Relative values (the value is then relative to the element’s current value) can be defined.
This is done by putting +=or -= in front of the value:
Example

$(“button”).click(function(){
$(“div”).animate({
left: ‘250px’,
height: ‘+=150px’,
width: ‘+=150px’

71
Advanced Java Script

});
});

(4) A property’s animation value can be specified as “show”, “hide”, or “toggle”:


Example
$(“button”).click(function(){
$(“div”).animate({
height: ‘toggle’
});
});

SHORT ANSWER QUESTION

Q.1. List out the JQuery CSS methods and describe them.
JQuery CSS Methods: The following table lists the JQuery CSS methods used to manipulate the
HTML and CSS.

JQuery CSS Method Description


1 css() Sets or returns one or more style properties for selected elements
2 height() Sets or returns the height of selected elements
3 width() Sets or returns the width of selected elements
4 innerHeight() Returns the height of an element (includes padding, but not border)
5 innerWidth() Returns the width of an element (includes padding, but not border)
6 outerHeight() Returns the height of an element (includes padding and border)
7 outerWidth() Returns the width of an elements(includes padding and border)
8 offset() Sets or returns the offset coordinates for selected elements (relative
to the document)
9 offsetParent() Returns the first positioned parent element
1 scrollLeft() Sets or returns the horizontal scrollbar position of selected elements
0
1 scrollTop() Sets or returns the vertical scrollbar position of selected elements
1

Q.2. List out the JQuery DOM manipulation methods and describe them.
JQuery DOM Manipulation Methods:
The following table lists the JQuery DOM Manipulation methods used to manipulate DOM.
JQuery DOM
Manipulation Method Description

1 html() Sets or returns the content of selected elements


2 text() Sets or returns the text content of selected elements

72
Advanced Java Script

3 replaceAll() Replaces selected elements with new HTML elements


4 replaceWith() Replaces selected elements with new content
5 remove() Removes the selected elements (including data and events)
6 detach() Removes selected elements (keeps data and events)
7 empty() Removes all child nodes and content from selected elements
8 after() Inserts content after selected elements
9 append() Inserts content at the end of selected elements
1 appendTo() Inserts HTML elements at the end of selected elements
0
1 before() Inserts content before selected elements
1
1 insertAfter() Inserts HTML elements after selected elements
2
1 insertBefore() Inserts HTML elements before selected elements
3
1 prepend() Inserts content at the beginning of selected elements
4
1 prependTo() Inserts HTML elements at the beginning of selected elements
5
1 clone() Makes a copy of selected elements
6
1 wrap() Wraps HTML element(s) around each selected element
7
1 wrapAll() Wraps HTML element(s) around all selected elements
8
1 wrapInner() Wraps HTML element(s) around the content of each selected
9 element

Q.3. List out the JQuery Event Object methods and describe them.
JQuery Event Object Methods: The following table lists the JQuery Event Object methods which
can be called on an event object.

JQuery Event Object Method Description


1 event.preventDefault() Prevents the default action of the event
2 event.isDefaultPrevented() Returns whether event.prevent Default() was called for
the event object
3 event.relatedTarget Returns which element being entered or exited on mouse
movement.
4 event.result Contains the last/previous value returned by an event
handler triggered by the specified event
5 event.stoplmmediatePropagation() Prevents other event handlers from being called
6 event.isImmediatePropagationStop Returns whether event.stopImmediatePropagation() was
ped() called for the event object

73
Advanced Java Script

7 event.stopPropagation() Prevents the event from bubbling up the DOM tree,


preventing any parent handlers from being notified of the
event
8 event.isPropagationStopped() Returns whether event.stopPropagation() was called for
the event object

Q.4. List out the JQuery Event Attributes and describe them.

JQuery Event Attributes: The following table lists the JQuery Event Attributes.

JQuery Attribute
Description
Method
1 event.data Contains the optional data passed to an event method when the
current executing handler is bound
2 event.pageX Returns the mouse position relative to the left edge of the document
3 event.pageY Returns the mouse position relative to the top edge of the document
4 event.screenX For mouse events, specifies the horizontal coordinate of the event
relative from the screen origin.
5 event.screenY For mouse events, specifies the vertical coordinate of the event
relative from the screen origin.
6 event.currentTarget The current DOM element within the event bubbling phase
7 event.delegateTarget Returns the element where the currently-called JQuery event
handler was attached
8 event.relatedTarget Returns which element being entered or exited on mouse
movement.
9 event.result Contains the last/previous value returned by an event handler
triggered by the specified event
1 event.target Returns which DOM element triggered the event
0
1 event.timeStamp Returns the number of milliseconds since January 1, 1970, when the
1 event is triggered
1 event.type Returns which event type was triggered (for example, click).
2
1 event.which Returns which keyboard key or mouse button was pressed for the
3 event (1 for left, 2 for middle, 3 for right).
1 Altkey Set to true if the Alt key was pressed when the event was triggered,
4 false if not. The Alt key is labeled Option on most Mac keyboards.
1 ctrlkey Set to true if the Ctrl key was pressed when the event was triggered,
5 false if not.
1 metakey Set to true if the Meta key was pressed when the event was
6 triggered, false if not. The Meta key is the Ctrl key on PCs and the

74
Advanced Java Script

Command key on Macs.


1 shiftkey Set to true if the Shift key was pressed when the event was
7 triggered, false if not.
1 keycode For keyup and keydown events, this returns the key that was
8 pressed.

Q.5. List out the JQuery effect methods and describe them.
JQuery Effect Methods: The following table lists the JQuery Effect Methods.

JQuery CSS Method Description

1 hide() Hides the selected elements.


2 show() Shows the selected elements.
3 toggle() Toggles between the hide() and show() methods.
4 slideDown() Slides-down (shows) the selected elements.
5 slideUp() Slides-up (hides) the selected elements.
6 slideToggle() Toggles between the slideUp() and slideDown() methods.
7 fadeIn() Fades in the selected elements.
8 fadeOut() Fades out the selected element.
9 fadeTo() Fades in/out the selected elements to a given opacity.
1 fadeToggle() Toggles between the fadeIn() and fadeOut() methods.
0
1 animate() Runs a custom animation on the selected elements.
1
1 stop() Stops the currently running animation for the selected elements.
2
1 finish() Stops, removes and completes all queued animations for the
3 selected elements.
1 queue() Shows the queued functions on the selected elements.
4
1 clearQueue() Removes all remaining queued functions from the selected
5 elements.
1 dequeue() Removes the next function from the queue, and then executes
6 the function.
1 delay() Sets a delay for all queued functions on the selected elements.
7

75
Advanced Java Script

76
Advanced Java Script

Unit – III
INTRO TO JQUERY UI
Essay Questions

Q.1. How to download JQuery UI.


JqueryUI library can be used in two ways in your web pages:
1. Downloading UI Library from its official website
2. Downloading UI Library from CDNs

1. Download UI Library from its Official Websites:


When you open the link http://jqueryui.com/, you will see there are three options to download
JqueryUI library:

(a) Custom Download: Click on this button to download a customized version of library.
(b) Stable: Click on this button to get the stable and latest version of JqueryUI library.
(c) Legacy: Click on this button to get the previous major release of the JqueryUI library.

Custom Download with Download Builder:

77
Advanced Java Script

Using Download Builder, user can create a custom build to include only those portions of the library
that are in need. User can download this new customized version of JqueryUI, depending on the
chosen theme. The following screen appears. (See Page 75)
This is useful when you require only specific plugins or features of the JqueryUI library. The
directory structure of this version is shown in the following figure.

CSS
/ Ui –
lightness/
Image
s/
Jquery – ui
-1.10.4.custom.CSS
Jquery – ui
-1.10.4.custom.min.CSS
Development –
bundle/
Js/
Jquery-1.10.2.js
Jquery – ui
-1.10.4.custom.js
Jquery – ui
-1.10.4.custom.min.js
Index.html

Uncompressed files are located in the development – bundle directory. The uncompressed file is best
used during development or debugging; the compressed file saves bandwidth and improves
performance in production.

Stable download:
Click on the Stable button, which leads directly to a ZIP file containing the sources, examples, and
documentation for latest version of JqueryUI library. Extract the ZIP file contents to a jqueryui
directory.
This version contains all files including all dependencies, a large collection of demos, and even the
library’s unit test suite. This version is helpful to getting started.

Legacy downloads:
Click on the Legacy button, which leads directly to a ZIP file of previous major release of JqueryUI
library. This version also contains all files including all dependencies, a large collection of demos,
and even the library’s unit test suite. This version is helpful to get you started.

2. Download UI Library from CDNs (JQuery UI with CDN):

A CDN or Content Delivery Network is a network of servers designed to serve files to users. If user
uses a CDN link in your web page, it moves the responsibility of hosting files from user’s own
servers to a series of external ones. This also offers an advantage that if the visitor to that webpage
has already downloaded a copy of JqueryUI from the same CDN, it won’t have to be re-downloaded.

The JQuery Foundation, Google, and Microsoft all provide CDNs that host JQuery core as well as
JqueryUI, because a CDN does not require you to host your own version of JQuery and JqueryUI.

78
Advanced Java Script

Q.2. Give the syntax of JQuery UI Interaction methods.


Syntax of JQuery UI Interaction Methods: The following table lists the syntax of JQuery UI
interaction methods.
JQuery UI
Interactive
Syntax
Plugin
Method
It can be used in two forms:
(a) $(selector, context).draggable (option) 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.
List of options are:
addClasses cursorAt iframeFix scrollSensitivity
appendTo delay opacity scrollSpeed
axis disabled refreshPositions snap
cancel distance revertDuration snapMode
connectToSortable grid revert snapTolerance
containment handle scope stack
draggable() cursor helper scroll z-index
(b) $(selector, context).draggable(“action, [params]) Method

The draggable (action, params) method can perform an action on the movable
elements, such as to prevent displacement. The actions which are nothing but
JQuery methods is specified as a string in the first argument and optionally, one or
more params can be provided based on the given action.
List of actions are:
destroy() option()
disable() option(options)
enable() option(optionName)
widget() option(optionName, Value)
droppable() It can be used in two forms:

(c) $(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.
List of options are:

accept greedy
activeClass hoverClass
addClasses scope
disabled tolerance
(d) $(selector, context).droppable(“action”, [params]) Method:

The droppable (“action”, params) method can perform an action on droppable

79
Advanced Java Script

elements, such as preventing droppable functionality. The action is specified as a


string in the first argument (e.g., “disable” to prevent the drop).
List of actions are:
destroy() option()
disable() option(options)
enable() option(optionName)
widget() option(optionName, Value)
It can be used in two forms:
(e) $(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.
List of options are:
alsoResize() cancel() Grid() Minwidth()
animate() containment() handles()
animateDuration( delay() Helper()
)
animateEasing() disabled() Maxheight()
Resizable() aspecRatio() distance() Maxwidth()
autoHide() Ghost() Minheight()
(f) $(selector, context).resizable(“action”, [params]) Method:

The resizable (“action”, params) method can perform an action on resizable


elements such as allowing or preventing resizing functionality. The action is
specified as a string in the first argument (e.g., “disable” to prevent the resize).
List of actions are:
destroy() option()
disable() option(options)
enable() option(optionName)
widget() option(optionName, Value)
Selectable() It can be used in two forms:
(g) $(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.
List of options are:
appendTo() disabled()
autoRefresh() distance()
cancel() filter()
delay() tolerance
(h) $(selector, context).selectable(“action”, [params]) Method:

The selectable(“action”, params) method can perform an action on selectable


elements, such as preventing selectable functionality. The action is specified as a
string in the first argument (e.g., “disable” to stop the selection).
List of actions are:

80
Advanced Java Script

destroy() option()
disable() option(options)
enable() option(optionName)
widget() option(optionName, Value)
refresh()
It can be used in two forms:
(i) $(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.
List of options are:
appendTo() disabled helper ScrollSpeed
axis distance Items Tplerance
cancel dropOnEmpty Opacity z-index
containment forceHelperSize Placeholder
cursor forcePlaceholderSize Revert
Sortable() cursorAt Grid Scroll
delay handle ScrollSensitivity.
(j) $(selector, context).sortable (“action”, [params]) Method:
The sortable (action, params) method can perform an action on the sortable
elements, such as to prevent displacement. The action is specified as a string in the
first argument and optionally. One or more params can be provided based on the
given action.
List of actions are:
destroy() option() refresh()
disable() option(options) refreshPositions()
enable() option(optionName) toArray(options)
widget() option(optionName, Value) Serialize (options)
cancel()

Q.3. Give the syntax of JQuery UI Widget methods.


Syntax of JQuery UI Widget Methods: The following table lists syntax of JQuery UI widget
methods.
JQuery UI
Widget plugin Description
Method
Accordion() It can be used in two forms:
(a) $(selector, context).accordion(options) Method:
The accordion (options) method declares that HTML elements and its contents
should be treated and managed as accordion menus. The options parameter is an
object that specifies the appearance and behavior of the menu involved.
List of options are:
active event
Animate Header
Collapsible Heightstyle

81
Advanced Java Script

disabled icons
(b) $(selector, context).accordion(“action”, [params]) Method:

The accordion (“action”, params) method can perform an action on accordion


elements. Such as selecting/de-selecting the accordion menu. The action is
specified as a string in the first argument (e.g., “disable” disables all menus).
List of actions are:
destroy() option() refresh()
disable() option(options)
enable() option(optionName)
widget() option(optionName, Value)
autocomplete() It can be used in two forms:
(c) $(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.
List of options are:
appendTo Minlength
autofocus position
Delay source
disabled
(d) $(selector, context).autocomplete (“action”, [params]) Method:

The autocomplete (“action”, params) method can perform an action on the list of
suggestions, such as show or hide. The action is specified as a String in the first
argument (e.g., “close” to hide the list).

List of actions are:

destroy() option() close()


disable() option(options) search([value])
enable() option(optionName)
widget() option(optionName, Value)
button() It can be used in two forms:
(d) $(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.
List of options are:
Disabled Label
icons text
(e) $(selector, context).button (“action”, [params]) Method:

The button (“action”, params) method can perform an action on buttons, such as
disabling the button. The action is specified as a string in the first argument (e.g.,

82
Advanced Java Script

“disable” to disable button).


List of actions are:
destroy() option() refresh()
disable() option(options)
enable() option(optionName)
widget() option(optionName, Value)
datepicker() It can be used in two forms:
(f) $(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.
List of options are:
accept greedy
activeClass hoverClass
addClasses scope
disabled tolerance
(g) $(selector, context).datePicker (“action”, [params]) Method:
The datepicker (action, params) method can perform an action on the calendar,
such as selecting a new date. The action is specified as a string in the first
argument and optionally, one or more params can be provided based on the
given action.
List of actions are:
destroy() option()
disable() option(options)
enable() option(optionName)
widget() option(optionName, Value)
refresh()
Dialog() It can be used in two forms-
(h) $(selector, context).dialog (option) 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.
List of options are:
Destroy option() widget
getDate option(options)
Hide option(optionName)
isDisabled option(optionName, Value)
setDate(date) Refresh()
Show() dialog( date[, onSelect] [, setting] [, pos])

(i) $(selector, context).dialog (“action”, [params]) Method:


The dialog (action, params) method can perform an action on the dialog box.
Such as closing the box. The action is specified as a string in the first argument
and optionally, one or more params can be provided based on the given action.

83
Advanced Java Script

List of actions are:


destroy() option() refresh()
disable() option(options) refreshPositions()
enable() option(optionName) toArray(options)
widget() option(optionName, Value) Serialize (options)
cancel()
Menu() It can be used in two forms:

(j) $(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.

List of options are:

Disabled Position
Icons Role
Menus
(k) $(selector, context).menu (“action”, [params]) Method:
The menu (“action”, params) method can perform an action on menu elements,
such as enabling/disabling the menu. The action is specified as a string in the
first argument (e.g., “disable” disables the menu).
List of action are:
Blur Enable option() nextPage
Collapse Expand option(options) Previous
collapseAll Focus option(optionName) previousPage
Destroy isFirstltem option(optionName, Value) Refresh
disable isLastltem Next widget
progressbar() It can be used in two forms:
(l) $(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.
List of options are:
Disabled
Max
value
(m) $(selector, context).progressbar (“action”, [params]) Method:
The progressbar (“action”, params) method can perform an action on progress
bar, such as changing the percentage filled. The action is specified as a string in
the first argument (e.g., “value” to change the percentage filled).
List of actions are:
destroy() option() Value()
disable() option(options)
enable() option(optionName)
widget() option(optionName, Value)

84
Advanced Java Script

slider() It can be used in two forms:


(n) $(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.
List of options are:
Animate Orientation Values
Max Range
Min Step
disabled Value
(o) $(selector, context).slider (“action”, [params]) Method:
The slider (“action”, params) method allows an action on the slider, such as
moving the cursor to a new location. The action is specified as a string in the first
argument (e.g., “value” to indicate a new value of the cursor).
List of actions are:
destroy() option() Value()
disable() option(options) Value(Value)
enable() option(optionName) Values()
widget() option(optionName, Value) Value(index, value)
spinner() It can be used in two forms:
(p) $(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
List of options are:
Culture Max Step
Disabled Min
Icons numberFormat
Incremental Page
(q) $(selector, context).spinner (“action”, [params]) Method:
The spinner (“action”, params) method can perform an action on spinner
elements, such as enabling/disabling the spinner. The action is specified as a
string in the first argument (e.g., “disable” disables the spinner).
List of actions are:
destroy() option() pageUp([pages])
disable() option(options) pageDown([pages])
enable() option(optionName) stepDown
widget() option(optionName, Value) setpUp
Value() Value(value)
tabs() It can be used in two forms:
(r) $(selector, context).tabs (options) Methods:
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

85
Advanced Java Script

appearance and behavior of tabs.


List of options are:
Active heightStyle
Collapsible Hide
Disabled show
event
(s) $(selector, context).tabs (“action”, [params]) Method:
The tabs (“action”, params) method allows an action on the tabs (through a
JavaScript program), selecting, disabling, adding, or removing a tab. The action is
specified as a string in the first argument (e.g., “add” to add a new tab).
List of actions are:
destroy() option() disable(index)
disable() option(options) enable(index)
enable() option(optionName) load(index)
widget() option(optionName, Value)
Cancel()
tooltip() It can be used in two forms:
(t) $(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.
List of options are:
Content Position
Disabled Show
Hide tooltipclass
Items Track
(u) $(selector, context).tooltip(“action, [params]) Method:
The tooltip (action, params) method can perform an action on the tooltip
elements, such as disabling the tooltip. The action is specified as a string in the
first argument and optionally, one or more params can be provided based on the
given action.
List of actions are:
destroy() option()
disable() option(options)
enable() option(optionName)
widget() option(optionName, Value)
Open() Close()

Q.4. Explain about consuming JQuery plugins from third party websites with an example.
JQuery plugins require JQuery to be present on a page in order to load properly. It works
under normal circumstances, but when creating a third-party widget, it will not load. Even if it is
loaded, it will not be used but instead loads own version of JQuery.
The solution is to wrap the plugin code within a function definition. Once the plugin has
loaded, call that function, passing it the JQuery object as its only argument.

86
Advanced Java Script

Example:
/*Main page.html*/
<!doctype html>
<head>
<title> Loading JQuery plugins from third-party scripts – Example 1</title>
<meta charset=“utf-8”>
</head>
<body>
<h1>Loading JQuery plugins from third-party script</h1>
<h2> Example 1 </h2>
<p id=“hello”>Widget will write content here</p>
<script src= “widget.js”></script>
</body>

JavaScript code of widget:

/*widget.js*/
(function(window, document) {“use strict”; /*Wrap code in an IIFE*/
Var JQuery, $;//Localize JQuery variables
Function loadScript(url, callback) {
/*Load script from url and calls callback once it’s loaded*/
Var scriptTag = document.createElement (‘script’);
scriptTag.setAttribute(“type”, “text/javascript”);
scriptTag.setAttribute(“src”, url);
if (typeof callback !== “undefined”) {
if (scriptTag.readyState) {
/*for old version of IE*/
ScriptTag.onreadystatechange = function() {
If (this.readyState === ‘complete’ || this.readyState=== ‘loaded’) {
Callback();
}
};
} else {
scriptTag.onload=callback;
}
}
(document.getElmentsByTagName(“head”)[0]||

87
Advanced Java Script

Document.documentElement).appendChild(scriptTag);
}
Function main() {
/* The main logic of our widget */
$(‘#hello’).html(‘This content comes from our widget’);
}
/*Load JQuery*/
loadScript(“…./jquery.js”, function() {
/* Restore $ and window.JQuery to their previous values and store the new JQuery in our local
JQuery variable.*/
$=JQuery=window.JQuery.noConflict(true);
Main(); /* Execute the main logic of our widget once JQuery is loaded*/
})
}(window, document)); /*end IIFE*/

Make use of a JQuery plugin to improve our widget:

/*plugin.js*/
Function initGreentifyPlugin(jQuery) {
(function ($) {
Var shade = “#556b2f”;
$.fn.greenify = function() {
This.css(“color”, shade);
Return this:
};
}(JQuery));
}

Updated widget code that calls plugin initializer and loads this plugins:

(function(window, document) {“use strict”; /*Wrap code in an IIFE*/


Var JQuery, $;//Localize JQuery variables
Function loadScript(url, callback) {
/*Same as before*/
}

88
Advanced Java Script

Function main() {
/*The main ogic of our widget*/
$(‘#hello’).html(‘This content comes from our widget’).greenify();
}
/*Load JQuery*/
loadScript(“…/jquery.js”, function() {
/*restore $ and window.JQuery to their previous values and store the new JQuery in our local
JQuery variables.*/
$=JQuery= window.JQuery.noConflict(true);
/*Load JQuery plugin and execute the main logic of our widget once the plugin is loaded is loaded*/
loadScript(“…/modified-jquery-plugin.js”, function() {
initGreenifyPlugin(JQuery);
main();
});
});

}(window, document));/*end IIFE*/

Q.5. Explain about JQuery validation plug-in.


Form validation generally happens on the server side where we check whether the data provided
by user or client is in correct format or not. If input data fails to satisfy the validation rules then the
server would have to send an error response code back to the client and request that the form be
resubmitted with correct information. This is really a lengthy process. We can overcome this
problem by validating the input data on client side. If the input data is incorrect, we will display the
error message and again ask the user to resubmitted the form with correct information.

JQuery Form Validation plugin is used to validate the form in the client side.

Types of validations:
1. Email Validation: Checks whether input field contains an email address.
2. NotEmpty Validation: Ensures that the field is not empty.
3. URL Validation: Ensures that the input is a valid url.
4. Regexp Validation: Ensures that a defined patterns is match character combinations in
string.
5. Length Validation: Checks whether input length is exact defined rules.
6. Min Length Validation: Ensures that input length should be greater than defined rules.
7. Phone Number Validation: Ensure that input is valid Mobile Number (Should be start
from 7 and exact 19 digit (This is for India Mobile Number))
8. Numeric Validation: Checks whether the field contains only numeric digits.

89
Advanced Java Script

To validate and form style:


1. First, we need to load Form validation js file to validate input fields and also use bootstrap css
file.
<!--Latest compiled and minified BootStarp CSS-->
<link rel=“stylesheet”
href=“https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css>
<!--JQuery library-->
<script src= “https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js”> </script>
<!--JQuery Form Validation library -->
<script src= “https://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js”>
</script>

2. Create a simple a form who has contain Name, Phone Number, Email, Website, Code, Filed
should be contain min length, Field should be contain only digits. We need to define Id of the
form. Let id id “myform”.

<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<!--Latest compiled and minified BootStarp CSS -->
<link rel=“stylesheet”
href=“https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css”>
<!-- JQuery library-->
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js”> </script>
<!--JQuery Form Validation library-->
<script src=“https://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js”>
</script>
</head>

<body>
<div id=“page-wrapper”>
<div class=“container”>
<h1> Form Validation</h1>
<form name=“myForm” class=“form-horizontal” id=“myForm” action=“#” method=“POST”
enctype=“multipart/form-data”>
<div class= “panel panel-info”>
<div class= “panel-heading”>Form validation</div>

90
Advanced Java Script

<div class= “panel-body”>


<div class= “row”>
<div class= “col-md-12”>
<div class= “col-md-6”>
<div class= “form-group”>
<label for=“name” class=“col-md-4”> Name* </label>
<div class= “col-md-6”>
<input type=“text” class=“form-control” name=“name” placeholder=“Enter Name” required/>
</div>
</div>

<div class= “form-group”>


<label for=“Mobile” class=“col-md-4”> Mobile* </label>
<div class=“col-md-6”>
<input type=“text” class=“form-control” name=“phone” placeholder=“Enter Mobile Number”
required/>
</div>
</div>
<div class= “form-group”>
<label for=“email” class=“col-md-4”> Email</label>
<div class=“col-md-6”>
<input type=“text” class=“form-control” name=“email” placeholder=“Enter Email”>
</div>
</div>
<div class=“form-group”>
<label for=“code” class=“col-md-4”> Code (Exact 11 digit)</label>
<div class=“col-md-6”>
<input type=“text” class=“form-control” name=“code” placeholder=“Enter code”>
</div>
</div>
<div class= “form-group”>
<label for=“code” class=“col-md-4”> Min Length </label>
<div class=“col-md-6”>
<input type=“text” class=“form-control” name=“min_length” placeholder=“Enter code”>
</div>
</div>
<div class= “form-group”>
<label for=“code” class=“col-md-4”> Number </label>
<div class= “col-md-6”>

91
Advanced Java Script

<input type=“text” class=“form-control” name=“number” placeholder=“Enter Only digits”>


</div>
</div>

<div class=“form-group”>
<label for=“url” class=“col-md-4”> Website </label>
<div class=“col-md-6”>
<input type=“text” class=“form-control” name=“url” placeholder=“Enter Url”>
</div>
</div>
</div>
<!-- end div-->
</div>
<!-- end div-->
</div>
</div>
</div>
<div class=“col-md-4 col-md-offset-4” style= “margin-bottom:50px;”>
<center>
<input type=“submit” class=“btn btn-primary” value= “Submit”/>
</center>
</div>
</form>
</div>
</div>
</body>
</html>
Form Validation

3. Define css to display error in the form


<style type=“text/css”>
#form.form-group label.error {
Color: #FB3A3A;

92
Advanced Java Script

Display: inline-block;
Margin: 0px 0 0px 0px;
Padding: 0;
Text-align: left;
}
</style>

4. Finally add JQuery to define rules to validate input field. In the validation, we will define rules
for specific input field name.

<script type= “text/javascript”>


(function ($, W, D)
{
var JQUERY4U={};
JQUERY4U.UTIL=
{
SetupForm Validation: function()
{
//form validation rules
$(“#myForm”).validate({
rules: {
name: “required”,
url: {
required: true,
url: true
},
phone: {
required: true,
minlength: 10,
pattern: [/^[7-9]{1}[0-9]{9}$/],
},
email: {
required: true,
email: true
},
code: {
required: true,
rangelength: [11, 11]
},
min_length: {
required: true,
minlength:3
},
number: {

93
Advanced Java Script

digits: true,
required: true,
minlength: 5
}
},
messages: {
name: “Please Enter Name”,
phone: “Please Enter Valid Mobile Number”,
email: “Please Enter valid Email”,
code: “please Enter 11 Digit code”,
min_length: “Please Enter Minimum 3 Digit”,
number: “Please Enter Only Digits”,
url: “Please Enter Websites Url”
},
submitHandler: function (form) {
form.submit();
}
});
}
}
//when the dom has loaded setup form validation rules
$(D).ready(function ($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(JQuery, window, document);
</script>

Form Validation

SHORT ANSWER QUESTIONS

Q.1. What is the need of JQuery UI in real websites.


1. JQuery promotes simplicity
2. JQuery elements display even when JavaScript is disabled

94
Advanced Java Script

3. Since JQuery pushes content to the client, it therefore reduces the wait time for server response.
4. JQuery makes animated applications just like Flash. It is smaller than Flash, so it results in
smoother playbacks and less errors.
5. Google and other search engines using page load time as one of the many factors affecting SEO.
JQuery pages load faster
6. It works anywhere. HTML5 is cross-browser compatible. So, it will work on any browser,
mobile phone or tablet, and even on Apple devices.
7. There’s a low learning curve. Since it’s based on plain old JavaScript, developers can learn
JQuery fast.
8. JQuery easily integrates with the Visual Studio IDE

9. Finally, JQuery is SEO friendly and CSS3 compliant.

Q.2. Define JQuery UI and describe the features of JqueryUI.


JqueryUI: JQuery UI is powerful Javascript library built on top of JQuery JavaScript library. UI
stands for User Interface and it is a set of plug-ins for JQuery that adds new functionalities to the
JQuery core library.
Features (set of plugins) of JQuery User Interface:
JQuery UI is categorized into four groups: 1. Interactions, 2. Widgets, 3. Effect, 4. Utilities.
The following table lists the features of JQuery UI.
S.N
JQuery UI feature Description
O
1 Interactions These are the interactive plugins, which gives the user the ability to
interact with DOM elements.
2 Widgets These are the plugins used to create user interface elements.
3 Effects These are built on the internal JQuery effects. They contain a full suite
of custom animations and transitions for DOM elements.
4 Utilities These are a set of modular tools the JqueryUI library uses internally.

Dialog Datapicker Droppable


Menu Resizable
Button
Progressbar Draggable
Widgets Autocomplete
Interaction Selectable
Slider Accordion
Spinner
Tabs Tooltip Sortable

JqueryUI Add Class


Color Animation

Effect
Utilities
Effects Hide
Toggle Class
Toggle Toggle Remove Class
Toggle Show
Switch Class

95
Advanced Java Script

Q.3. List out the methods of JqueryUI plugin and describe them.
JqueryUI Interaction Methods:
The following table lists the JqueryUI Interaction Methods:
S.N JqueryUI Interactive plugin
Description
o Method
1 draggable() Allow elements to be moved using the mouse
2 droppable() Used to reate targets for draggable elements.
3 resizable() Used to change the size of an element using the mouse
4 selectable() Used to select elements, individually or in a group using
the mouse
5 sortable() Used to reorder elements in list or grid using the mouse.

JqueryUI Widget Methods:


The following table lists the JqueryUI widget methods:
S.N JqueryUI Widget
Description
O plugin Method
1 accordion() It is a JQuery based expandable and collapsible content holder that is
broken into sections for presenting information in a limited amount of
space and probably looks like tabs.
2 autocomplete() It is used 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.
3 button() It is used to transform the HTML elements (like buttons, inputs and
anchors) into themeable buttons, with automatic management of
mouse movements on them.
4 datepicker() It is used to create a datepicker and changes the appearance of HTML
elements on a page by adding new CSS classes.
5 dialog() It is used to transform the HTML code written on the page into HTML
code to display a dialog box.
6 menu() It can be used for inline and popup menus, or as a base for building
more complex menu systems
7 progressbar() It is used to create progress bars which indicate the status (completion
percentage) of an operation or process.
8 slider() It is used whenever a numeric value within a certain range is to be
obtained and changes the appearance of HTML elements in the page,
adding new CSS classes that give them the appropriate style.
9 spinner() It is used to create a spinner which adds an up/down arrow to the left
of a input box allowing a user to increment/ decrement a value in the
input box.
10 tabs(0 A single content area with multiple panels, each associated with a
header in a list that allow users to quickly flip between them to and
changes the appearance of HTML elements inside the page.
11 tooltip() It is used to add tooltip to any element on which you want to display

96
Advanced Java Script

tooltip.

97
Advanced Java Script

JqueryUI Effect Methods: The following table lists the JqueryUI Effect methods:
S.N JqueryUI Effect plugin
Description
o Method
1 Color Animation Animate the properties of elements between colors.
2 Easing Apply an easing equation to an animation
3 Effect effect() method applies an animation effect to the elements
without having to show or hide it.
4 Hide effect() method applies an animation effect to hide elements.
5 Show show() method displays an item using the indicated effect.
6 Toggle Toggles the show() or hide() methods depending on whether the
element is hidden or not.
7 Toggle class adds or removes one or more classes from each element in the set
of matched elements.
8 Add class Add specified classes to the matched elements while animating all
style changes
9 Remove class Removes the specified classes to the matched elements while
animating all style changes.
10 Switch class Move from one CSS one CSS class to another, animating the
transition from one state to the other.

Q.4. Give the syntax of JqueryUI Effect methods.


Syntax of JqueryUI Effect Methods: The following table lists the JqueryUI effect methods:

S.N JqueryUI Effect


Syntax
o plugin Method

1 Color Animation selector.animate({any number of CSS properties separated separated by


comma});
2 Easing
3 Effect .effect(effect [, options] [, duration] [, complete]) effects that can be used
with the effects() method
Blind fade Scale
bounce Fold Shake
Clip highlight size
Drop Puff Slide
explode pulsate transfer
4 Hide .hide(effect [, options] [, duration ] [, complete])
5 Show .show(effect [, options] [, duration ] [, complete])
6 Toggle .toggle(effect [, options] [, duration ] [, complete])
7 Toggle class .toggleClass (className [, switch] [, duration ] [, easing ] [, complete])

98
Advanced Java Script

8 Add class $(selector, context).addClass (className, options)


List of options are:
Easing Children
duration complete queue
9 Remove class .removeClass(className [, option])
10 Switch class .switch Class(remove ClassName, add ClassName [, duration] [, easing ] [,
complete])

Q.5. Give the syntax of JqueryUI utility methods.


Syntax of JqueryUI Utility Methods: The following table lists the JqueryUI Utility methods:
S.N JqueryUI Utility
Syntax
o plugin Method
1 Position .position (options)
Lists of options are:
My Off Using
At collision within
2 Widget factory JQuery.widget (name [, base ], prototype) Base widget is
the widget used by the widget factory.
List of options are:
disablehide
hide
show
List of methods are:
_create() _focusable(element) _hide(element,
option[, callback])
_delay( fn [, delay]) _getCreateEventDate(0 _hoverable( element)
_destroy() _getCreateOptions() _init()

Q.6. Explain about JQuery themes.


JQuery themes: JQuery has two different styling themes, A and B, each with different colors for
buttons, bars, content blocks, and so on.
The syntax of jquery theming is <div data-role=“page” data-theme= “a|b”>
Example:
<!DOCTYPE html>
<html>
<head>
<meta name= “viewport” content= “width=device-width, initial-scale=1”>
<link rel= “stylesheet” href= “https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css”>
<script src= “https://code.jquery.com/jquery-1.11.3.min.js”> </script>
<script src= “https://code.jquery.com/jquery-1.11.3.min.js”> </script>
<script src= “https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js”> </script>

99
Advanced Java Script

</head>
<body>
<div data-role=“page” id=“pageone” data-theme=“a”>
<div data-role= “header”> <h1> Vikas Publishers </h1> </div>
<div data-role= “main” class= “ui-content”>
<p> Text link</p>
<a href=“#” > A Standard Text Link</a>
<a href=“#” class=“ui-btn”> Link Button</a>
<p> A List View: </p>
<ul data-role=“listview” data-autodividers=“true” data-inset=“true”>
<li> <a href=“#” >Android </a> </li>
<li> <a href=“#” > IOS </a></li>
</ul>

<label for= “fullname”> Input Field:</label>


<input type=“text” name=“fullname” id=“fullname” placeholder=“Name..”>
<label for=“switch”> Toggle Switch: </label>

<select name=“switch” id=“switch” data-role=“slider”>


<option value= “on”> On </option>
<option value= “off” selected> Off </option>
</select>
</div>

<div data-role= “footer”> <h1> Vikas Publishers </h1> </div>


</div>
</body>
</html>

Example:
<!DOCTYPE html>
<html>
<head>
<meta name=“viewport” content=“width=device-width, initial-scale=1”>
<link rel=“stylesheet” href= “https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css”>
<script src= “https://code.jquery.com/jquery-1.11.3.min.js”> </script>
<script src= “https://code.jquery.com/jquery-1.11.3.min.js”> </script>
<script src= “https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js”> </script>
</head>
<body>

100
Advanced Java Script

<div data-role=“page” id=“pageone” data-theme=“b”>


<div data-role= “header”> <h1> Vikas Publishers </h1> </div>
<div data-role= “main” class= “ui-content”>
<p> Text link</p>
<a href=“#” > A Standard Text Link</a>
<a href=“#” class=“ui-btn”> Link Button</a>
<p> A List View: </p>
<ul data-role=“listview” data-autodividers=“true” data-inset=“true”>
<li> <a href=“#” >Android </a> </li>
<li> <a href=“#” > IOS </a></li>
</ul>

<label for= “fullname”> Input Field:</label>


<input type=“text” name=“fullname” id=“fullname” placeholder=“Name..”>
<label for=“switch”> Toggle Switch: </label>

<select name=“switch” id=“switch” data-role=“slider”>


<option value= “on”> On </option>
<option value= “off” selected> Off </option>
</select>
</div>

<div data-role= “footer”> <h1> Vikas Publishers </h1> </div>


</div>
</body>
</html>

Q.7. How to Customize JQuery UI widgets / plug-ins.


Customizing JqueryUI widgets/ plug-ins: Widget factory is used to create stateful JQuery plugins
using the same abstraction as all JQuery UI widgets.

The JQuery UI Widget Factory is simply a function ($.widget) that takes a string name and an object
as arguments and creates a JQuery plugin and a “Class” to encapsulate its functionality.

Syntax
JQuery.widget(name [, base ], prototype)

Example:
Create : function() creates custom control, _setOption function is used to define an options
object which stores the default values for all of the options, Move method, that shifts the button a
specified horizontal distance. Firing an event when if the button moves beyond x=400

101
Advanced Java Script

<!DOCTYPE html>
<html>
<head>
<meta charset= “utf-8”>
<title> JQuery UI Widget – Default functionality </title>
<link rel=“stylesheet” href= “//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css”>
<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>
<script>
$(function() {
$.widget(“P.myButton”, {
_create: function() {
this_button=$(“<button>”);
this_button.text(“My first Widget Button”);
this_button.width(this.options.width)
this_button.css(“background-color”, this.option.color);
this_button.css(“position”, “absolute”);
this_button.css(“left”, “100px”);
$(this.element).append(this_button);
},
move: function(dx) {
var x=dx + parselnt(this.__button.css(“left”));
this._buton.css(“left”, x);
If(x>400) {this._trigger(“outbounds”, {}, {position:x});}
}
});
$(“#button4”).myButton();
$(“#button4”).on(“mybuttonoutbounds”, function(e, ui) {
alert(“out”);
});
$(“#button4”).myButton(“move”, 500);
});
</script>
</head>
<body>
<div id= “button4”> </div>
</body>
</html>

102
Advanced Java Script

UNIT – IV
INTRO TO AJAX
Essay Questions

Q.1. Explain how to insert, delete, and update data into database using jquery-ajax.
Insert data into database using jquery-ajax with PHP: To insert data into a database, a
connection must be obtained with the database. The following function establishes a connection
with the database.

public function _construct() {


If(!$this->db) {
//Connect to the database
$conn=new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
If($conn->connect_error) {
die(“Failed to connect with MySQL:”.$conn->connect_error);
}else{
$this->db=$conn;
}
}
}
Once the connection is established, data can be inserted into the database. The following function
can be used to insert the given data into a database.

public function insert($table, $data){


If(!empty($data) && is_array($data)) {
$columns= “;
$values= “;
$i=0;
If(!array_key_exists(‘created’,$data)) {
$data[‘created’]=date(“Y-m-d H:i:s”);
}
If(!array_key_exists(‘modified’, $data)) {
$data[‘modified’]=date(“Y-m-d H:i:s”);
}
foreach($data as $key=>$val) {
$pre=($i>0)?‘,’:”;
$columns .=$pre.$key;
$values .=$pre.“ ”’.$val.“ ”’;
$i ++;
}
$query= “INSERT INTO”.$table.“ (“.$columns.”) VALUES (“.$values.”)”;

103
Advanced Java Script

$insert= $this-> db-> query($query);


return $insert?$this->db->insert_id:false;
}else{
return false;
}
}

Update data into database using jquery-ajax with PHP:


To update data into a database, a connection must be obtained with the database. The following
function establishes a connection with the database.

public function _construct() {


If(!$this->db) {
//Connect to the database
$conn=new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
If($conn->connect_error) {
die(“Failed to connect with MySQL:”.$conn->connect_error);
}else{
$this->db=$conn;
}
}
}

Once the connection is established, data can be updated into the database. The following function
can be used to update the given data into a database.

public function update($table, $data, $conditions) {


If(!empty($data) && is_array($data)) {
$colvalSet= “;
$whereSql= “;
$i=0;
If(!array_key_exists(‘modified’, $data)) {
$data[‘modified’]=data(“Y-m-d H:i:s”);
}

foreach($data as $key=>$val) {
$pre=($i>0)?’, ‘:”;
$colvalSet .=$pre.$key.“=“‘.$val.” ”’;
$i++;
}
If(!empty($conditions)&& is_array($conditions)){
$whereSql .=‘WHERE’;

104
Advanced Java Script

$i=0;
foreach($conditions as $key=>$value) {
$pre=($i>0)?‘AND’:”;
$whereSql .=$pre.$key.“= ‘“.$value.” ”’;
$i++;
}
}
$query=“UPDATE”.$table. “SET”.$colvalSet.$whereSql;
$update= $this->db->query($query);
return $update?$this->db->affected_rows:false;
}else{
return false;
}
}

Delete data from database using jquery-ajax with PHP:


To delete data from a database, a connection must be obtained with the database first. The
following function establishes a connection with the database.
public function _construct() {
If(!$this->db) {
//Connect to the database
$conn=new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
If($conn->connect_error) {
die(“Failed to connect with MySQL:”.$conn->connect_error);
}else{
$this->db=$conn;
}
}
}

Once the connection is established, data can be deleted from the database. The following function
can be used to delete the specified data from a database.

public function delete($table, $conditions) {


$whereSql .=”;
If(!empty($conditions)&& is_array($conditions)){
$whereSql .=‘WHERE’;
$i=0;
foreach($conditions as $key=>$value) {
$pre=($i>0)?‘AND’:”;
$whereSql .=$pre.$key.“= ‘“.$value.” ”’;

105
Advanced Java Script

$i++;
}
}
$query=“DELETE FROM”.$table.$whereSql;
$delete= $this->db->query($query);
return $delete?true:false;
}

Q.2. Explain about grid development using JQuery-Ajax.


To get a client side and server side data in a Grid View using JQuery and Ajax.
1. Create a table in a .aspx page of our Application and will also add two buttons in it to get the
data, either from the client side or from the server side.
2. Now add a Script Tag and under that do the coding for the runtime evaluation and data binding.
3. Now we will add the data for the client and server side.
4. Now a function will be created to call the associated data on Successful execution of the code or
if it’s not executed successfully then it will lead to an error.

Example:
STEP 1
<div>
<input id=“clientworkers” type=“button” value=“Get Client Workers Data”
onclick=“clientworkersdatabind()”/>
<asp:Button Text=“Get Server Workers Data” runat=“server” ID=“Serverworkers”OnClientClick=
“javascript:return serverworkersdatabind()”/>
<br/>
<br/>
<table id= “Workerstable”>
<thead>
<tr>
<th> Employee Name</th>
<th> Post</th>
<th> Age </th>
<th> Working in</th>
<th>DataSource</th>
</tr>
</thead>
</table>
</div>

STEP 2:
<script id=“workersTemplate” type= “text/html”>
<tr>
<td>$(EmployeeName)</td>

106
Advanced Java Script

<td>${Post}</td>
<td>{{if Age>30}}
<span style=‘background-color:red’> Middle-aged</span>
{{else}}
<span style=‘background-color:yellow’>Still young</span>
{{/if}}</td>
<td>${Workingin}</td>
<td>${DataSource}</td>
</tr>
</script>

STEP 3:
To add the data to the client side add the following code to the .aspx page:
<script type= “text/javascript”>
function clientworkersdatabind(){
var workers= [
{EmployeeName: “Anubhav”, Post: “Developer”, Age: 24, Workingin: “IT”, DataSource: “Client”},
{EmployeeName: “Ashwini”, Post: “Trainee”, Age: 24, Workingin: “IT”, DataSource: “Client”},
{EmployeeName: “Dinesh”, Post: “Senior Manager”, Age: 35, Workingin: “HR”, DataSource: “Client”},
{EmployeeName: “Swati”, Post: “Tester”, Age: 27, Workingin: “Testing”, DataSource: “Client”},
{EmployeeName: “Hari”, Post: “Trainer”, Age: 40, Workingin: “IT”, DataSource: “Client”},
]
BindTable(workers);
}
To add the data to the server side go to the aspx.cs page and add this code:
Public static object ServerWorkers()
{
List<object> workers=new List<object>();
Worker.Add(new{EmployeeName=“Anubhav”, Post=“Developer”, Age:=45, Workingin=“IT”,
DataSource=“Server”});
Worker.Add(new{EmployeeName=“Ashwini”, Post=“Trainee”, Age=38, Workingin=“IT”,
DataSource=“Server”});
Worker.Add(new{EmployeeName=“Dinesh”, Post=“Senior Manager”, Age=20, Workingin=“HR”,
DataSource=“Server”});
Worker.Add(new{EmployeeName=“Swati”, Post=“Tester”, Age=27, Workingin=“Testing”,
DataSource=“Server”});
Worker.Add(new{EmployeeName=“Hari”, Post=“Trainer”, Age=25, Workingin: “IT”,
DataSource=“Server”});

107
Advanced Java Script

Return workers;

STEP 4:
function serverworkersdatabind() {
$.ajax({
type: “POST”,
url: “JQueryGridTemplate.aspx/ServerWorkers”,
data: “{}”,
contentType: “application/json; charset=utf-8”,
dataType: “json”,
success:function(msg, status, metaData) {
if(msg.d && msg.d.length>0) {
BindTable(msg.d);
}
},
error:function(ex, status) {
Alert(“error”);
},
complete:function(eret, tyty) {
}
});
Return false;
}

Q.3. Explain about JSON objects.


(a) JSON objects are surrounded by curly braces {}.
(b) JSON objects are written in key/value pairs.
(c) Keys must be strings, and values must be a valid JSON data type(string, number, object,
array, boolean or null).
(d) Keys and values are separated by a colon.
(e) Each key/value pair is separated by a comma.

108
Advanced Java Script

Accessing JSON objects: the object values can be accessed by using dot(.) notation:

<!DOCTYPE html>
<html>
<body>
<p>Access a JSON object using dot notation:</p>
<p id=“demo”></p>
<script>
var myObj, x;
myObj={“name”:“John”, “age”:30, “car”:null};
x=myObj.name;
document.getElementByld(“demo”).innerHTML=x;
</script>
</body>
</html>

The object values can also be accessed by using bracket ([]) notation:
<!DOCTYPE html>
<html>
<body>
<p>Access a JSON object using bracket notation:</p>
<p id=“demo”></p>
<script>
var myObj, x;
myObj={“name”:“John”, “age”:30, “car”:null};
x=myObj[“name”];
document.getElementByld(“demo”).innerHTML=x;
</script>
</body>
</html>

Looping an Object: Looping is done through object properties by using the for-in loop:
myObj={“name”:“John”, “age”:30, “car”:null};
for(x in myObj){
document.getElementByld(“demo”).innerHTML +=x;
}

In a for-in loop, the bracket notation is used to access the property values:
myObj={“name”:“John”, “age”:30, “car”:null};
for(x in myObj){
document.getElementByld(“demo”).innerHTML +=myObj[x];
}

109
Advanced Java Script

Nested JSON Objects (Complex JSON objects): Values in a JSON object can be nested into another
JSON object. These objects and arrays will be passed as values assigned to keys, and typically will be
comprised of key-value pairs as well.

myObj={
“name”: “John”,
“age”:30,
“cars”:{
“car1”: “Ford”,
“car2”: “BMW”,
“car3”: “Fiat”
}
}

Curly braces are used throughout to form a nested JSON object and just like any other value, when
using objects, commas are used to separate elements.

Nested JSON objects can be accessed by using the dot notation or bracket notation:
x=myObj.cars.car2;
//or:
x=myObj.cars[“car2”];

Modify Values: the dot notation can be used to modify any value in a JSON object:
myObj.cars.car2= “Mercedes”;

The bracket notation can also be used to modify a value in a JSON object:
myObj.cars[“car2”]= “Mercedes”;

Delete Object Properties: Use the delete keyword to delete properties from a JSON object:
delete myObj.cars.car2;

SHORT ANSWER QUESTIONS

Q.1. Explain the need of AJAX in real websites.


AJAX is the asynchronym for Asynchronous JavaScript and XML. AJAX is a technique for
creating fast and dynamic web pages. It allows web pages to be updated asynchronously by
exchanging small amounts of data with the server behind the scenes. This means that, it is possible
to update parts of a web page, without reloading the whole page, whereas, classic web pages,
(which do not use AJAX) must reload the entire page if the content should change.
Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.
Ajax is not a programming language or a tool, but a concept. Ajax is a client-side script that
communicates to and from a server/database without the need for a postback or a complete page

110
Advanced Java Script

refresh. Ajax can be defined as “the method of exchanging data with a server, and updating parts of
a web pages – without reloading the entire page.”
Ajax itself is mostly a generic term for various JavaScript techniques used to connect to a web
server dynamically without necessarily loading multiple pages. In a more narrowly –defined sense,
it refers to the use of XmlHttpRequest objects to interact with a web server dynamically via
JavaScript.

Benefits of Ajax: There are four main benefits of using Ajax in web applications:
1. Callbacks: Ajax is used to perform a callback, making a quick round trip to and from the server
to retrieve and/or save data without posting the entire page back to the server. By not
performing a full postback and sending all form data to the server, network utilization is
minimized and quicker operations occur. In sites and locations with restricted bandwidth, this
can greatly improve network performance. Most of the time, the data being sent to and from the
server is minimal. By using callbacks, the server is not required to process all form elements. By
sending only the necessary data, there is limited processing on the server. There is no need to
process all form elements, process the ViewState, send images back to the client, or send a full
page to the client.
2. Making Asynchronous Calls: Ajax allows you to make asynchronous calls to a web server. This
allows the client browser to avoid waiting for all data to arrive before allowing the user to act
once more.
3. User-Friendly: Because a page postback is being eliminated, Ajax enabled applications will
always be more responsive, faster and more user-friendly.
4. Increased Speed: The main purpose of Ajax is to improve the speed, performance and usability
of a web application. A great example of Ajax is the movie rating feature on Netflix. The user
rates a movie and their personal rating for that movie will be saved to their database without
waiting for the page to refresh or reload. These movie ratings are being saved to their database
without posting the entire page back to the server.

Q.2. How to get database data using JQuery – AJAX?


(1) HTML file to retrieve data from Database:
<html>
<script type=“text/javascript” src=“jquery-1.3.2.js”> </script>
<script type=“text/javascript”>
$(document).ready(function() {
$(#display”).click(function(){
$.ajax({
type: “GET”,
url:“dataselect.php”,
dataType:“html”, //expected html to be returned
success: function(response) {

111
Advanced Java Script

$(“#responsecontainer”).html(response);
}
});
});
});
</script>
<body>
<h3 align=“center”>Manage Student Details</h3>
<table border=“1” align=“center”>
<tr>
<td><input type=“button” id=“display” value=“Display All Data”/> </td>
</tr>
</table>
<div id=“responsecontainer” align=“center”> </div>
</body>
</html>

(2) PHP file to connect database and retrieve data from Database:
<?php
$con=mysqli_connect(“localhost”, “root”, “”);
If(!$con)
{
die(‘Could not connect: ‘. mysqli_error());
}
mysqli_select_db(“samples”, $con);
$result=mysqli_query(“select *from student”, $con);
echo “<table border= ‘1’>
<tr>
<td align=center> <b> Roll No </b></td>
<td align=center> <b> Name </b></td>
<td align=center> <b> Address </b></td>
<td align=center> <b>Stream</b></td>
<td align=center> <b>Status</b></td>”;
while ($data=mysqli_fetch_row($result))
{
echo “<tr>”;
echo “<td align=center>$data[0]</td>”;
echo “<td align=center>$data[1]</td>”;
echo “<td align=center>$data[2]</td>”;
echo “<td align=center>$data[3]</td>”;

112
Advanced Java Script

echo “<td align=center>$data[4]</td>”;


echo “</tr>”;
}
echo “</table>”;
?>

Q.3. Discuss about the syntax of JSON.


JSON (JavaScript Object Notation) is a format for sharing data. As its name suggests, JSON is derived
from the Javascript programming language, but it’s available for use by many languages including
Python, Ruby, PHP, and Java. JSON is usually pronounced like the name “Json”.
JSON uses the .json extension when it stands alone. When it’s defined in another file format (as in
.html), it can appear inside of quotes as a JSON string, or it can be an object assigned to a variable.
This format is easy to transmit between web server and client or browser.

JSON Syntax Rules:


JSON Syntax is derived from JavaScript object notation syntax:
(a) Data is in name/value pairs
(b) Data is separated by commas
(c) Curly braces hold objects
(d) Square brackets hold arrays

JSON Data – A Name and a Value:


(a) JSON data is written as name/value pairs.
(b) A name/value pair consists of a field name (in double quotes), followed by a colon,
followed by a value:
“name”: “John”
(c) JSON names require double quotes. JavaScript names don’t.

JSON Values:
In JSON, values must be one of the following data types:
(a) a string
(b) a number
(c) an object(JSON object)
(d) an array
(e) a boolean
(f) null

In JavaScript values can be all of the above, plus any other valid JavaScript expression, including:
(a) a function
(b) a date
(c) undefined

In JSON, string values must be written with double quotes:


{“name”: “John”}

113
Advanced Java Script

114
Advanced Java Script

Q.4. Explain about reading JSON objects using JQuery.


JSON is short for JavaScript Object Notation and is a way to store information in an
organized, easy-to-access manner. JQuery provides a method called “parseJSON” which takes a
well-formed JSON string and returns the resulting JavaScript object.

$(document).ready(function(){
var jsonp=‘[{ “Lang”:“JQuery”, “ID”:“1”}, { “Lange”: “C#”, “ID”: “2”}]’;
var lang= “;
var obj=$.parseJSON(jsonp);
$.each(obj, function() {
Lang+=this[‘Lang’] + “<br/>”;
});
$(‘span’).html(lang);
});_

Q.5. Explain about JSON arrays.


(a) Arrays in JSON are almost the same as arrays in JavaScript.
(b) In JSON, array values must be of type string, number, object, array, boolean or null.
(c) In JavaScript, array values can be all of the above, plus any other valid JavaScript expression,
including functions, dates, and undefined.

Arrays in JSON Objects:


Arrays can be values of an object property:
{
“name”: “John”,
“age”:30,
“cars”: [ “Ford”, “BMW”, “Fiat”]
}

Accessing Array Values: The array values can be accessed by using the index number:
x=myObj.cars[0];

Looping Through an Array: array values can be accessed by using a for-in loop:
for (i=0; i<myObj.cars.length; i++){
x += myObj.cars[i];
}

Nested Arrays in JSON Objects: Values in an array can also be another array, or even another JSON
object:
myObj={

“name”: “John”,

115
Advanced Java Script

“age”:30,
“cars”:[
{“name”:“Ford”, “models”:[“Fiesta”, “Focus”, “Mustang”]},
{“name”:“BMW”, “models”:[“320”, “X3”, “X5”]},
{“name”:“Fiat”, “models”:[“500”, “Panda”]}
]
}

To access arrays inside arrays, for-in loop is used for each array:
for (i in myObj.cars) {
x+=“<h1>”+myObj.cars[i].name+ “</h1>”;
for (j in myObj.cars[i].models) {
x+= myObj.cars[i].models[j];
}
}

Modify Array Values: The index number is used to modify an array:


myObj.cars[1]= “Mercedes”;

Delete Array Items: The delete keyword is used to delete items from an array:
delete myObj.cars[1];

Q.6. List out the JQuery Ajax method and describe them.
jQuery Ajax Methods:
S.N
Methods Description
o
1 jQuery.ajax(options) Load a remote page using an HTTP request.
2 jQuery.ajaxSetup(options) Setup global settings for AJAX requests.
3 jQuery.get(url, [data], [callback], Load a remote page using an HTTP GET request.
[type])
4 jQuery.getSON(url, [data], Load JSON data using an HTTP GET request.
[callback])
5 jQuery.getScript (url, [callback]) Load and executes a JavaScript file using an HTTP GET
request.
6 jQuery.post(url, [data], [callback], Load a remote page using an HTTP POST request.
[type])
7 load(url, [data], [callback]) Load HTML from a remote file and inject it into the
DOM.
8 serialize() Serializes a set of input elements into a string of data.
9 serializeArray() Serializes all forms and form elements like the
.serialize() method but returns a JSON data.

116
Advanced Java Script

UNIT – V
INTRO TO ANGULAR JS
Essay Questions

Q.1. How to download AngularJS.

Open the link https://angularjs.org/ there are two options to download AngularJS library:

1. View on GitHub – Click on this button to go to GitHub and get all of the latest scripts.
2. Download AngularJS 1 – Or click on this button, a screen as below would be seen:
Download AngularJS

3. This screen gives various options of using Angular JS as follows:


i. Downloading and hosting files locally:

117
Advanced Java Script

1.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.
2.We can also go with the minified, uncompressed or zipped version.
ii. CDN 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. This means using CDN
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 AngularJS from the same CDN, it won’t have to be re-
downloaded.
iii. Try the new AngularJS 2: Click on this button to download AngularJS beta 2
version. This version is very fast, mobile supported and flexible compare to legacy
and latest of AngularJS 1.

Q.2. Explain about AngularJS Expressions?


AngularJS Expressions: AngularJS binds data to HTML using Expressions. It can be written inside
double braces. {{expression }} or inside a directive: ng-bind= “expression”. It will resolve the
expression, and return the result exactly where the expression is written.
AngularJS expressions are much like JavaScript expression: They can contain literals, operators,
and variables.
Example {{5+5}} or {{firstName+ “ ” + lastName}}
<!DOCTYPE html>
<html>
<script src= “https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js”> </script>
<body>
<div ng-app=“ ”>
<p>My first expression:{{5+5}}</p>
</div>
</body>
</html>

On removing the ng-app directive, HTML will display the expression as it is, without solving it:
<!DOCTYPE html>
<html>
<script src= “https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js”> </script>
<body>
<div>
<p>My first expression:{{5+5}}</p>
</div>
</body>
</html>

118
Advanced Java Script

AngularJS change the value of CSS properties. The color of the input box can be changed by
changing its value:
<div ng-app=“” ng-init=“myCol= ‘lightblue’”>
<input style= “background-color:{{myCol}}” ng-model= “myCol” value= “{{myCol}}”>
</div>

AngularJS Numbers:
AngularJS numbers are like JavaScript numbers:
<div ng-app=“” ng-init=“quantity=1; cost=5”>
<p>Total in dollar:{{quantity*cost}}</p>
</div>

Same example using ng-bind:


<div ng-app=“ ” ng-init=“quantity=1; cost=5”>
<p>Total in dollar:<span ng-bind=“quantity*cost”></span></p>
</div>

AngularJS strings: AngularJS strings are like JavaScript strings:


<div ng-app= “ ” ng-init= “firstName= ‘John’:lastName= ‘Doe’”>
<p> The name is {{firstName+ “ ” + lastName}} </p>
</div>

Same example using ng-bind:


<div ng-app= “ ” ng-init= “firstName= ‘John’:lastName= ‘Doe’”>
<p> The name is <span ng-bind=“firstName+ ‘ ’ + lastName”></span> </p>
</div>

AngularJS Objects: AngularJS objects are like JavaScript objects:


<div ng-app=“ ” ng-init=“person= {firstName:‘John’, lastName:‘Doe’}”>
<p> The name is {{person.lastName}} </p>
</div>

Same example using ng-bind:


<div ng-app=“ ” ng-init=“person= {firstName:‘John’, lastName:‘Doe’}”>
<p> The name is <span ng-bind=“person.lastName”></span> </p>
</div>

AngularJS Arrays: AngularJS arrays are like JavaScript arrays:


<div ng-app=“ ” ng-init=“points=[1,15,19,2,40]”>

119
Advanced Java Script

<p> The third result is {{points[2]})</p>


</div>

Same example using ng-bind:


<div ng-app=“ ” ng-init=“points=[1,15,19,2,40]”>
<p> The third result is <span ng-bind=“points[2]”></span> </p>
</div>

AngularJS Expressions vs. JavaScript Expressions:


1. Like JavaScript expressions, AngularJS expressions can contain literals, operators, and variables.
2. Unlike JavaScript expressions, AngularJS expressions can be written inside HTML.
3. AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript
expressions do.
4. AngularJS expressions support filters, while JavaScript expressions do not.

Example: testAngularJS.htm combining all the above


<html>
<head>
<title>AngularJS Expressions</title>
</head>
<body>
<h1>Sample Application</h1>
<div ng-app=“ ” ng-init= “quantity=1;cost=30; student={firstName:‘Technical’,
lastName:‘Publishers’,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>
<script src=“https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js”> </script>
</body>
</html>

Q.3. Explain about AngularJS Modules?


AngularJS supports modular approach. Modules are used to separate logics say services,
controllers, application etc. and keep the code clean. We define modules in separate js files and
name them as per the module.js file. There are two types of modules.
(a) Application Module: used to initialize an application with controller(s).
(b) Controller Module: used to define the controller.

120
Advanced Java Script

Application Module: An application module is created by using the AngularJS function


angular.module

<div ng-app= “myApp”>…</div>


<script>
var app=angular.module(“myApp”,[]);
</script>

The “myApp” parameter refers to an HTML element in which the application will run.
Controllers, directives, filters can be added to the module created.
Controller Module:
studentController.js
mainApp.controller(“studentController”,function($scope) {
$scope.student={
firstName: “Technical”,
lastName: “Publishers”,
fees:500,
subjects:[
{name: ‘Physics’, marks:70},
{name: ‘Chemistry’, marks:80},
{name: ‘Math’, marks:65},
{name: ‘English’, marks:75},
{name: ‘Hindi’, marks:67},
],
fullName:function() {
var studentObject;
studentObject=$scope.student;
return studentObject.firstName + “ ” + studentObject.lastName;
}
};
});

A controller studentController module is declared using mainApp.controller function.


Using Modules:
<div ng-app=“mainApp” ng-controller= “studentController”>
……
<script src= “mainApp.js”></script>
</div>

121
Advanced Java Script

Application module is used by using ng-app directive and controller by using ng-controller
directive.
Example:
<html>
<head>
<title>AngularJS Modules</title>
<script src=“https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js”> </script>
<script src= “/angularjs/src/module/mainApp.js”> </script>
<script src= “/angularjs/src/module/studentController.js”> </script>
<style>
table, th, td {
border:1px solid grey;
border-collapse:collapse;
padding:5px;
}
table tr:nth-child(odd){
background-color:#f2f2f2;
}
table tr:nth-child(even){
background-color:#ffffff;
}
</style>
</head>

<body>
<h2> AngularJS Sample Application</h2>
<div ng-app= “mainApp” ng-controller=“studentController”>
<table border= “0”>
<tr>
<td>Enter first name:</td>
<td> <input type= “text” ng-model= “student.firstName”></td>
</tr>
<tr>
<td>Enter last name:</td>
<td> <input type= “text” ng-model= “student.lastName”></td>
</tr>
<tr>
<td>Name:</td>

122
Advanced Java Script

<td>{{student.fullName()}}</td>
</tr>
<tr>
<td>Subject:</td>
<td>
<table>
<tr>
<th>Name</th>
<th>Marks</th>
</tr>
<tr ng-repeat= “subject in student.subjects”>
<td>{{subject.name}}</td>
<td>{{subject.marks}}</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</body>
</html>

Q.4. Explain about AngularJS Controllers?


AngularJS Controllers: AngularJS application mainly relies on controllers to control the
flow of data in the application. A controller is defined using ng-controller directive. A controller is a
JavaScript object containing attributes/properties and functions. Each controller accepts $scope as
a parameter which refers to the application / module that controller is to control.

<div ng-app=“ ” ng-controller= “studentController”>


……
</div>

A controller is a JavaScript Object, created by a standard JavaScript object constructor.


AngularJS Controller Example:
<script>
function studentController($scope){
$scope.student={
firstName: “Technical”,
lastName: “Publishers”,
fullname: function(){

123
Advanced Java Script

var studentObject;
studentObject=$scop.student;
return studentObject.firstName +“ ” + studentObject.lastName;
}
};
}
</script>

(a) studentController defined as a JavaScript object with $scope as argument.


(b) $scope refers to application which is to use the studentController object.
(c) $scope.student is property of studentController object.
(d) firstName and lastName are two properties of $scope.student object. We have passed the
default values to them.
(e) fullname is the function of $scope.student object whose task is to return the combined
name.
(f) In fullName function we’re getting the student object and then return the combined name.
(g) As a note, we can also define the controller object in separate JS file and refer that file in the
html page.
studentController’s student property can be used using ng-model or using expressions as follows.
Enter first name: <input type= “text” ng-model= “student.firstName”></br>
Enter last name: <input type= “text” ng-model= “student.last Name”><br>
<br>
You are entering: {{student.fullNa6me()}}

(a) We have bounded student.firstName and student.lastname to two input boxes,


student.fullName() to HTML.
(b) If anything is typed in first name and last name input boxes, fullname will be updated
automatically.
Example
testAngularJS.htm makes use of controller.
<html>
<head>
<title>AngularJS Controller</title>
<script src= “https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js”></script>
</head>

<body>
<h2> AngularJS Sample Application</h2>
<div ng-app=“mainApp” ng-controller=“studentController”>
Enter first name: <input type=“text” ng-model=“student.firstName”> <br> <br>

124
Advanced Java Script

Enter last name: <input type=“text” ng-model=“student.lastName”> <br> <br>


You are entering: {{student.fullName()}}
</div>
<script>
var mainApp=angular.module(“mainApp”,[]);
mainApp.controller(‘studentController’, function($scope){
firstName: “Technical”,
lastName: “Publishers”,
fullName: function(){
var studentObject;
studentObject=$scope.student;
return studentObject.firstName + “ ” + studentObject.lastName;
}
};
});
</script>
</body>
</html>

Q.5. Explain about AngularJS Scope.


AngularJS Scope: 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 objects.
<script>
var mainApp=angular.module(“mainApp”, []);
mainApp.controller(“shapeController”, function($scope){
$scope.message=“In shape controller”;
$scope.type=“Shape”;
});
</script>

(a) $scope is passed as first argument to controller during its constructor definition.
(b) $scope.message and $scope.type are the models which are to be used in the HTML page.
(c) We have set values to models which will be reflected in the application module whose
controller is shapeController.
(d) We can define functions as well in $scope.
Scope Inheritance: Scope are controllers specific. If we define nested controllers then child
controller will inherit the scope of its parent controller.

<script>
var mainApp=angular.module(“mainApp”,[]);
mainApp.controller(“shapeController”, function($scope){

125
Advanced Java Script

$scope.message=“In shape controller”;


$scope.type=“Shape”;
});
mainApp.controller(“circleController”, function($scope){
$scope.message= “In circle controller”;
});
</script>

(a) Set values to models in shapeController.


(b) Overridden message in child controller circleController. When “message” is used within module
of controller circleController, the overridden message will be used.
Example
<html>
<head>
<title> AngularJS Forms</title>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app=“mainApp” ng-controller=“shapeController”>
<p> {{message}}<br/>{{type}}</p>
<div ng-controller= “circleController”>
<p> {{message}}<br/>{{type}}</p>
</div>
<div ng-controller= “squareController”>
<p> {{message}}<br/>{{type}}</p>
</div>
</div>
<script src=“https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js”> </script>
<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”;
});
mainApp.controller(“squareController”, function($scope){
$scope.message=“In square controller”;

126
Advanced Java Script

$scope.type=“Square”;
});
</script>
</body>
</html>

Q.6. Explain about AngularJS Dependency Injection?


AngularJS Dependency Injection: 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.
1. Value
2. Factory
3. Service
4. Provider
5. Constant
1. Value: Value is simple javascript object and it is used to pass values to controller during config
phase:
//define a module
var mainApp=angular.module(“mainApp”,[]);

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


mainApp.value(“defaultInput”,5);
……

//inject the value in the controller using its name “defaultInput”


mainApp.controller(‘CalcController’, function($scope, CalcService, defaultInput) {
$scope.number=defaultInput;
$scope.result=CalcService.square($scope.number);

$scope.square=function() {
$scope.result=CalcService.square($scope.number);
}
});

2. 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.
//define a module

127
Advanced Java Script

var mainApp=angular.module(“mainApp”,[]);

//create a factory “MathService” which provides a method multiply to return multiplication of two
numbers
mainApp.factory(‘MathService’, function() {
var factory={};

factory.multiply=function(a, b) {
return a*b
}
return factory;
});
//inject the factory “MathService” in a service to utilize the multiply method of factory.
mainApp.service(‘CalcService’, function(MathService){
this.square=function(a){
return MathServce.multiply(a,a);
}
});
…..

3. 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.
//define a module
var mainApp=angular.module(“mainApp”,[]);

//create a service which defines a method square to return square of a number.


mainApp.service(‘CalcService’, function(MathService){
this.square=function(a){
return MathService.multiply(a,a);
}
});

//inject the service “CalcService” into the controller


mainApp.controller(‘CalcController’, function($scope, CalcService, defaultInput)

{
$scope.number=defaultInput;
$scope.result=CalcService.square($scope.number);
$scope.square=function(){
$scope.result=CalcService.square($scope.number);
}
});

128
Advanced Java Script

4. 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
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.
//define a module
var mainApp=angular.module(“mainApp”,[]);

//create a service using provider which defines a method square to return square of a number.
mainApp.config(function($provide) {
$provide.provider(“MathService’, function() {
this.$get=function(){
var factory={};
factory.multiply=function(a,b){
return a*b;
}
return factory;
};
});
});

(5) 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”);
example

<html>

<head>

<title>AngularJS Dependency Injection</title>

</head>

<body>

<h2>AngularJS Sample Application</h2>

<div ng-app= “mainApp” ng-controller= “CalcController”>

<p>Enter a number:<input type= “number” ng-model= “number”/> </p>

<button ng-click= “square()”>X<sup>2</sup></button>

<p> Result:{{result}}</p>

129
Advanced Java Script

</div>

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

130

You might also like