Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Jquery Print

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 101

ADVANCED JAVA SCRIPT - JQUERY

UNIT – I
Introduction:
jQuery is a fast and concise JavaScript Library created by John Resig in 2006 with: Write less,
do more. jQuery simplifies HTML document traversing, event handling, animating, and Ajax
interactions for rapid web development.

jQuery was first released in January 2006 by John Resig at BarCamp NYC. It is currently
headed by Timmy Wilson and maintained by a team of developers. Nowadays, jQuery is widely
used technology. Most of the websites are using jQuery.
jQuery Release History:
Let's see the release dates of jQuery versions.

Version No. Release Date


1.0 26,August,2006
1.1 14,January,2007
1.2 10, September, 2007
1.11 24, January, 2014
2.0 18, April, 2013
2.1 24, January, 2014
Q). What is jQuery?
jQuery is a JavaScript toolkit designed to simplify different tasks by writing less code. jQuery
is a small, light-weight and fast JavaScript library. It is cross-platform and supports different types
of browsers. It is also referred as ? write less do more.

The important features supported by jQuery:


 DOM manipulation − The jQuery made it easy to select DOM elements, and modifying
their content by using cross-browser open source selector engine.
 Event handling − The jQuery offers to capture a wide variety of events, such as a user
clicking on a link, without the need to clutter the HTML code itself with event handlers.
 AJAX Support − The jQuery helps you a lot to develop a responsive and feature rich set of
AJAX technology.
 Animations − The jQuery comes with plenty of built-in animation effects which we can use
in websites.
 Lightweight − The jQuery is very lightweight library - about 19KB in size (Minified and
zipped).
 Cross Browser Support − The jQuery has cross-browser support, and works well in IE
6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 1


 Latest Technology − The jQuery supports CSS3 selectors and basic XPath syntax.

What are the jQuery Features?


The important features of jQuery:

 HTML manipulation
 DOM manipulation
 DOM element selection
 CSS manipulation
 Effects and Animations
 Utilities
 AJAX
 HTML event methods
 JSON Parsing
 Extensibility through plug-ins
Why jQuery is required?
Sometimes, a question can arise that what is the need of jQuery or what difference it makes on
bringing jQuery instead of AJAX/ JavaScript? If jQuery is the replacement of AJAX and JavaScript?
For all these questions, you can state the following answers.
 It is very fast and extensible.
 It facilitates the users to write UI related function codes in minimum possible lines.
 It improves the performance of an application.
 Browser's compatible web applications can be developed.
 It uses mostly new features of new browsers.

A lot of JavaScript frameworks, jQuery is the most popular and the most extendable. Many
of the biggest companies on the web design using jQuery.
Some of these companies are:
 Microsoft
 Google
 IBM
 Netflix

How to use jQuery? There are two ways to use jQuery.


 Local Installation: download jQuery library on your local machine and include it in your HTML code.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 2


 CDN Based Version : include jQuery library into your HTML code directly from Content Delivery
Network (CDN).

Local Installation
 Go to the https://jquery.com/download/ to download the latest version available.

 Now put downloaded jquery-2.1.3.min.js file in a directory of your website, e.g. /jquery.


jQuery Examples:

jQuery is developed by Google. To create the first jQuery example, you need to use
JavaScript file for jQuery. You can download the jQuery file from jquery.com or use the absolute
URL of jQuery file. In jQuery example, we are using the absolute URL of jQuery file. The jQuery
example is written inside the script tag.
A simple example of jQuery: File Name: firstjquery.html

<!DOCTYPE html>  
<html>   <head>  
 <title>First jQuery Example</title>  
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">  
 </script>  
 <script type="text/javascript" language="javascript">  
 $(document).ready(function() {  
 $("p").css("background-color", "cyan");    });  
 </script>  </head>  
<body>  
<p>The first paragraph is selected.</p>   <p>The second paragraph is selected.</p>  
<p>The third paragraph is selected.</p>   </body>   </html>  
Result:
The first paragraph is selected.

The Second paragraph is selected.

The Thrid paragraph is selected.

Example 2: Now you can include jquery library in your HTML file as follows :

<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript" src = "/jquery/jquery-2.1.3.min.js">
</script>
<script type = "text/javascript">
$(document).ready(function() {
document.write("Hello, World!");
});
</script> </head>

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 3


<body>
<h1>Hello</h1>
</body> </html>

How to Call a jQuery Library Functions?


Using jQuery reads or manipulates the document object model (DOM), we need to make
sure that we start adding events etc. as soon as the DOM is ready.

If you want an event to work on your page, you should call it inside the $
(document).ready() function. Everything inside it will load as soon as the DOM is loaded and
before the page contents are loaded. It register a ready event for the document as follows :
$(document).ready(function()
{
// do stuff when DOM is ready
});

To call any jQuery library function, use HTML script tags as shown below :

<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() {alert("Hello, world!");});
});
</script> </head>
<body>
<div id = "mydiv">
Click on this to see a dialogue box.
</div>
</body>
</html>

How to Use Custom Scripts?


It is better to write our custom code in the custom JavaScript file : custom.js, as follows:

/* Filename: custom.js */
$(document).ready(function() {
$("div").click(function() {
alert("Hello, world!");
}); });

Now we can include custom.js file in our HTML file as follows : L

<html>

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 4


<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" src = "/jquery/custom.js">
</script>
</head>
<body>
<div id = "mydiv">
Click on this to see a dialogue box.
</div> </body> </html>

JQuery Basics:
Q). What are the basics of JQuery basics?
jQuery is a framework built-in using JavaScript capabilities(elements). So we can using all
functions and other capabilities available in JavaScript. The basic concepts are frequently used in
jQuery.

1. Numbers

2. Strings

3. Booleans

4. Objects

5. Arrays

6. Functions with Arguments

7. Scope

8. Built-in Functions.

1. Numbers : Numbers in JavaScript are double-precision 64-bit format IEEE 754 values. They are
just as strings.
5350
120.27
0.26

2. String : A string in JavaScript is an immutable object that contains none, one or many characters.
"This is JavaScript String"
'This is JavaScript String'

3. 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.
true // true
false // false

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 5


0 // false
1 // true
"" // false "hello" // true

4. Objects: JavaScript supports Objects concepts and to create an object using object literal are:
var emp = {
name: "Zara",
age: 10 };

write and read properties of an object using the dot(.) notation:


// Getting object properties
emp.name // ==> Zara
emp.age // ==> 10
// Setting object properties
emp.name = "Daisy" // <== Daisy
emp.age = 20 // <== 20

5. Arrays : Array is a collection of Homogeneous data elements, which are stored in a single
memory location. An array has a length property that is useful for iteration:
var x = [];
var x = [1, 2, 3, 4, 5];
for (var i = 0; i < x.length; i++)
{
// Do something with x[i]
}

6. Functions: A function in JavaScript can be either named or anonymous. A named function can be
defined using function keyword.

function named()
{
// do some stuff here
}

A function can be defined in similar way as a normal function but it can not have any name.
A function can be assigned to a variable or passed to a method.

var handler = function ()


{
// do some stuff here
}

JQuery makes a use of anonymous functions very frequently as follows:

$(document).ready(function(){
// do some stuff here
});

7. Arguments: JavaScript variable arguments is a kind of array which has length property.


Following example explains.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 6


function func(x)
{
console.log(typeof x, arguments.length);
}
func(); //==> "undefined", 0
func(1); //==> "number", 1
func("1", "2", "3"); //==> "string", 3

The arguments object also has a callee property, which refers to the function:

function func() {
return arguments.callee;
}
func(); // ==> func

8. Context : JavaScript always refers to the current context. Within a function this context can
change, depending on the function. To specify the context for a function call using the function-
built-in methods call() and apply() methods.

$(document).ready(function() {
// this refers to window.document
});
$("div").click(function() {
// this refers to a div DOM element
});

9. Scope : The scope of a variable is the region(portion) of a program in which it is defined.


JavaScript variable have two types of scopes.
 Global Variables − A global variable has global scope which means it is defined everywhere in your
JavaScript code.
 Local Variables − A local variable will be visible only within a function where it is defined. Function
parameters are always local to that function.

Within the body of a function, a local variable takes precedence over a global variable with the
same name.

10. Callback : A callback is a plain JavaScript function passed to some method as an argument or
option. Some callbacks are just events, called to give the user a chance to react when a certain
state is triggered. jQuery's event system uses such callbacks everywhere:

$("body").click(function(event) {
console.log("clicked: " + event.target);
});

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 7


Most callbacks provide arguments and a context. In the event-handler the callback is called with
one argument, as an Event.

11. Built-in Functions: JavaScript comes along with a useful set of built-in functions. These methods
can be used to manipulate Strings, Numbers and Dates.
The Following JavaScript functions are:
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.
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 string value converted to lower case.
toUpperCase(): Returns the string value converted to uppercase.
toString():Returns the string representation of the number's value.

jQuery Selectors: Q). Explain about JQuery Selectors?

jQuery Selectors are used to select and manipulate HTML elements. They are very
important part of jQuery library. With jQuery selectors, to find or select HTML elements based on
their id, classes, attributes, types and much more from a DOM.
The selectors are used to select one or more HTML elements using jQuery and once the
element is selected then its perform various operation on that.
Note : All jQuery selectors start with a dollor sign and parenthesis e.g. $(). It is known as the
factory function.
Every jQuery selector start with this sign $(). This sign is known as the factory function. It
uses the three basic building blocks while selecting an element in a given document. So in case
using any other JavaScript library where $ sign is conflicting with some thing else then you can
replace $ sign by jQuery name and you can use function jQuery() instead of $().

S.No Selector Description


Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 8
.
1 Tag It represents a tag name available in the DOM.
Name: Ex: $('p') selects all paragraphs'p'in the document.
2 Tag ID: It represents a tag available with a specific ID in the DOM.
Ex : $('#real-id') selects a specific element in the document that has an
ID of real-id.
3 Tag Class: It represents a tag available with a specific class in the DOM.
Ex : $('real-class') selects all elements in the document that have a
class of real-class.

How to use Selectors: The jQuery selectors can be used single or with the combination of other
selectors. They are required at every steps while using jQuery. They are used to select the exact
element in HTML document.

S.No. Selector Description


1) Name: It selects all elements that match with the given element name.
2) #ID: It selects a single element that matches with the given id.
3) .Class: It selects all elements that matches with the given class.
4) Universal(*) It selects all elements available in a DOM.
5) Multiple E,F,G It selects combined results of all specified selectors A,B and C.

1. jQuery -Element Name Selector: The element selector selects all the elements that have
a tag name of T.
Syntax: $('tagname')
 Parameters: Here is the description of all the parameters used by this selector .
 tagname : Any standard HTML tag name like div, p, em, img, li etc.
Returns: Like any other jQuery selector, this selector also returns an array filled with the found
elements. Example:
 $('p') − Selects all elements with a tag name of p in the document.
 $('div') − Selects all elements with a tag name of div in the document.
Example:

<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 class = "myclass">This is a paragraph.</p>
<p id = "myid">This is second paragraph.</p>
<p>This is third paragraph.</p>
</div>

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 9


</body>
</html>

Result :
This is a paragraph.

This is second paragraph.


This is third paragraph.

2. jQuery - Element ID Selector: The element ID selector selects a single element with the
given id attribute.
Syntax: $('#elementid')
Parameters : Here is the description of all the parameters used by this selector.
Elementid: It is an element ID. If the id contains any special characters like periods(.) or colons, to
escape those characters with backslashes.
Example:
$('#myid') − Selects a single element with the given id myid.
$('div#yourid') − Selects a single division with the given id yourid.
3. jQuery - Element Class Selector: The element class selector selects all the elements
which match with the given class of the elements.
Syntax: $('.classid')
Parameters: Here is the description of all the parameters used by this selector −
classid − This is class ID available in the document.
Ex:
 $('.big') − Selects all the elements with the given class ID big.
 $('p.small') − Selects all the paragraphs with the given class ID small.
 $('.big.small') − Selects all the elements with a class of big and small.

4. jQuery - Universal Selector


The universal selector selects all the elements available in the document.
Syntax: $('*') * − A symbolic star.

Ex: $('*') selects all the elements available in the document.

5. jQuery - Multiple Elements Selector


The Multiple Elements selector selects the combined results of all the specified electors
E, F or G. It can specify any number of selectors to combine into a single result. Here order of the
DOM elements in the jQuery object aren't necessarily identical.
Syntax : $('E, F, G,....')
All the parameters used by this selector:
 E − Any valid selector
 F − Any valid selector
 G − Any valid selector

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 10


The selector also returns an array filled with the found elements.
Ex:
$('div, p') − selects all the elements matched by div or p.
$('p strong, .myclass') − selects all elements matched by strong that are descendants of an
element matched by ‘p’ as well as all elements that have a class of myclass.
$('p strong, #myid') − selects a single elements matched by strong that is descendant of an
element matched by ‘p’ as well as element whose id is myid.
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(".big, #div3").css("background-color", "yellow");
});
</script>
</head>
<body>
<div class="big" id="div1">
<p>This is first division of the DOM.</p>
</div>
<div class="medium" id="div2">
<p>This is second division of the DOM.</p>
</div>
<div class="small" id="div3">
<p>This is third division of the DOM</p>
</div>
</body>
</html>

Result:
This is first division of the DOM.
This is second division of the DOM.
This is third division of the DOM

Selectors Examples
Selector Name Description
$('*') This selector selects all elements in the document.
$("p > *") It selects all elements that are children of a paragraph element.
$("#specialID") This selector function gets the element with id="specialID".
$(".specialClass") It gets all the elements that have the class of specialClass.
$("li:not(.myclass)") Selects all elements matched by <li>not have lass="myclass".
$("a#specialID.specialClass") It matches links with an specialID and a class of specialClass.
$("p a.specialClass") It matches links with a class of specialClass declared within <p> elements.
$("p:empty") Selects all elements matched by <p> that have no children.
$("div[p]") Selects all elements matched by <div> that contain an element matched by
<p>.
Note : We can use all the above selectors with any HTML/XML element in generic way. For example if selector $
("li:first") works for <li> element then $("p:first") it also work for <p> element.

Java Query DOM Attributes


Q). Explain about Java Query Attributes?

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 11


The basic components are used to manipulate the DOM elements to the properties and
attributes assigned to JQ elements. Most of these attributes are available through JavaScript as
DOM node properties.
Some of the more common properties are:
 className
 tagName
 id
 href
 title
 rel
 src
the following Syntax for an image element:

<img id="myImage" src="image.gif" alt="An image"


class="someClass" title="This is an image"/>
In this element's, the tag name is ‘img’, and id, src, alt, class, and title represents the
element's attributes, each of which consists of a name and a value.

jQuery gives to easily manipulate an element's attributes and gives access to the element so
that we can also change its properties. There are some of the attributes are used to assign the
properties.
1. Get Attribute Value
2. Set Attribute Value
3. Applying Styles.
1.Get Attribute Value: The attr() method can be used to either fetch the value of an attribute
from the first element in the set attribute values onto all matched elements.
Ex:
The Following example which fetches title attribute of <em> tag and set <div id="divid"> value
with the same value:
2. Set Attribute Value: The attr(name, value) method can be used to set the named attribute
onto all elements in the wrapped set using the passed value.
3. 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.
Ex: 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>
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 12
Result:

Attribute Methods:
Methods Description
1. attr( properties ) Set a key/value object as properties to all matched elements.
2. attr( key, fn ) Set a single property to a value, on all matched elements.
3. removeAttr( name ) Remove an attribute from each of the matched elements.
4. hasClass( class ) Returns true if the specified class is present on at least one of the set
of matched elements.
5. removeClass( class ) Removes all or the specified class(es) from the set of matched
elements.
6. toggleClass( class ) Adds the specified class if it is not present, removes the specified class
if it is present.
7. html( ) Get the html contents (innerHTML) of the first matched element.
8. html( val ) Set the html contents of every matched element.
9. text( ) Get the combined text contents of all matched elements.
10. text( val ) Set the text contents of all matched elements.
11. val( ) Get the input value of the first matched element.

Example 1 :
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("p#pid").click(function () {
$(this).toggleClass("red");
}); });
</script>
<style>
.red { color:red; }
</style> </head>
<body>
<p class="green">Click following line to see the result</p>
<p class="red" id="pid">This is first paragraph.</p>
</body> </html>

Result: Click the following line to see the result

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 13


This is first paragraph.

Example 2:
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript" src="/jquery/jquery-1.3.2.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var content = $("input").val();
$("p#pid2").text(content);
});
</script>
<style>
.red { color:red; }
.green { color:green; }
</style> </head>
<body>
<input type="text" value="First Input Box"/>
<input type="text" value="Second Input Box"/>
<p class="green" id="pid1">This is <i>first paragraph</i>.</p>
<p class="red" id="pid2">This is second paragraph.</p>
</body> </html>

Result:

JQuery DOM Traversing


Q). What is JQuery Traversing ?and explain?
jQuery traversing, which means "move through", are used to "find" (or select) HTML
elements based on their relation to other elements.

jQuery is a very powerful tool which provides a variety of DOM traversal methods to helps
the select elements in a document randomly as well as in sequential method. Most of the DOM
Traversal Methods do not modify the jQuery object and they are used to filter out
elements from a document based on given conditions.

Syntax:
$('selector expression').find('selector expression to find child elements');

Java Query DOM Traversing methods are to implement the concepts are:
1. Find Element by Index
2. Filtering
3. Locating Descending element. and etc…
The image below Example an HTML page as a tree (DOM tree). With jQuery traversing, you can
easily move up (ancestors), down (descendants) and sideways (siblings) in the tree, starting from
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 14
the selected (current) element. This movement is called traversing - or moving through - the DOM
tree.

The jQuery library includes various methods to traverse DOM elements in a DOM
hierarchy. The following jQuery methods for traversing DOM elements are:

Methods Description
children() To get all the child elements of the specified elements.
parent() Get the parent of the specified element(s).
each() Iterate over specified elements and execute specified call back
function for each element.
find() Get all the specified child elements of each specified element(s).
first() Get the first occurrence of the specified element
next() Get the immediately following sibling of the specified element.
prev() Get the immediately preceding sibling of the specified element.
siblings() Get the siblings of each specified element(s)
offsetParent() Returns a jQuery collection with the positioned parent of the first
matched element.
1. Find Elements by Index:

Every list has its own index, and can be located directly by using eq(index) Method.
Every child element starts its index from zero, thus, list item 2 would be accessed by using $
("li").eq(1) and so on.

<html>
<head>
<title>the title</title>
</head> <body> <div> <ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul> </div> </body> </html>

Result:
 list item 1
 list item 2
 list item 3
 list item 4
 list item 5
 list item 6

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 15


2. 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). The selector can be written using any
selector.
<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>
3. Locating Descendent Elements:
The find( selector ) method can be used to locate all the descendent elements of a
particular type of elements. The selector can be written using any selector.
<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() {
$("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>
Result:

This is 1st paragraph and THIS IS RED


This is 2nd paragraph and THIS IS ALSO RED

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 16


Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 17
UNIT – II

JQUERY – CSS METHODS:


The jQuery library supports nearly all of the selectors included in Cascading Style Sheet
(CSS) specifications, as outlined on the World Wide Web Consortium's(w3c) site.
Using JQuery library developers can enhance their websites without worrying about
browsers and their versions as long as the browsers have JavaScript enabled. Most of the JQuery
CSS Methods do not modify the content of the jQuery object and they are used to apply CSS
properties on DOM elements.
Q). Explain about the JavaQuery CSS methods?
The jQuery library supports nearly all of the selectors included in Cascading Style Sheet
(CSS) specifications 1 through 3, as outlined on the World Wide Web Consortium's site.
The CSS property to query should be specified using the CSS property name, not the
JavaScript property name (e.g. background-color instead of backgroundColor).
jQuery CSS() Methods:
The css() methods are to sets or returns one or more style properties for the selected elements in
web applications.
1. Apply CSS Properties: This is very simple to apply any CSS property using JQuery method
css( PropertyName, PropertyValue ).
Syntax for the method:
selector.css( PropertyName, PropertyValue );

The CSS properties are :


i. Return a CSS property.
ii. Set a CSS property.
iii. Set Multiple CSS properties.
Return a CSS Property: To return the value of a specified CSS property, use the following syntax:
css("propertyname");
Ex:
$("p").css("background-color");
Set a CSS Property: To set a specified CSS property, use the following syntax:
css("propertyname","value");
Ex: $("p").css("background-color", "yellow");
Set Multiple CSS Properties: To set multiple CSS properties, use the following syntax:
css({"propertyname":"value","propertyname":"value",...});
Ex: $("p").css({"background-color": "yellow", "font-size": "200%"});

2. Apply Multiple CSS Properties:


To apply multiple CSS properties using a single JQuery method CSS( {key1:val1,
key2:val2....). You can apply as many properties as you like in a single call.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 18


Syntax :
selector.css( {key1:val1, key2:val2....keyN:valN})

Example 1:
<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).css({"color":"red",
"background-color":"green"});
}); </script> </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>
Result:
 list item 1
 list item 2
 list item 3
 list item 4
3. Setting Element Width & Height:
The width( val ) and height( val ) method can be used to set the width and height
respectively of any element. Following simple example which sets the width of first division
element whereas rest of the elements have width set by style sheet:
Example:
<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() {
$("div:first").width(100);
$("div:first").css("background-color", "blue");
}); </script>
<style>
div{ width:70px; height:50px; float:left; margin:5px;
background:red; cursor:pointer; }
</style> </head>
<body>
<div></div>
<div>d</div>
<div>d</div>
<div>d</div>
<div>d</div> </body>
</html>

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 19


Result:

d d d

4. jQuery CSS() Methods:


JQuery CSS Methods Following table lists down all the methods which we can use to play
with CSS properties:
Methods Description
css( name, value) Set a single style property to a value on all matched elements.
css( properties ) Set a key/value object as style properties to all matched elements.
height( val ) Set the CSS height of every matched element.
innerHeight( ) Gets the inner height (excludes the border and includes the
padding) for the first matched element.
innerWidth( ) Gets the inner width (excludes the border and includes the
padding) for the first matched element.
offset( ) Get the current offset of the first matched element, in pixels,
relative to the document
offsetParent( ) Returns a jQuery collection with the positioned parent of the first
matched element.
outerHeight( [margi Gets the outer height (includes the border and padding by
n] ) default) for the first matched element.
outerWidth( [margi Get the outer width (includes the border and padding by default)
n] ) for the first matched element.
position( ) Gets the top and left position of an element relative to its offset
parent.
scrollLeft( val ) When a value is passed in, the scroll left offset is set to that value
on all matched elements.
width( val ) Set the CSS width of every matched element.
Example:
<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() {
$("div").click(function () {
var color = $(this).css("background-color");
var height = $(this).innerHeight();
$("#result").html("Inner Height is <span>" +
height + "</span>.");
$("#result").css({'color': color,
'background-color':'gray'});
$("#result").height( height );
}); });
</script> <style>
#div1{ margin:10px;padding:12px;
border:2px solid #666;
width:60px;}

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 20


#div2 { margin:15px;padding:5px;
border:5px solid #666;
width:60px;}
#div3 { margin:20px;padding:4px;
border:4px solid #666;
width:60px;}
#div4 { margin:5px;padding:3px;
border:3px solid #666;
width:60px;}
</style> </head> <body>
<p>Click on any square:</p>
<span id="result"> </span>
<div id="div1" style="background-color:blue;"></div>
<div id="div2" style="background-color:pink;"></div>
<div id="div3" style="background-color:#123456;"></div>
<div id="div4" style="background-color:#f11;"></div>
</body>
</html>
This will produce the following result:

JQuery-DOM Manupulation Methods:


Q). Explain about Jquery DOM manipulation methods?
JQuery provides methods to manipulate DOM in efficient way. It can not need to write big
code to modify the value of any element's attribute or to extract HTML code from a paragraph or
division.
JQuery provides methods such as .attr(), .html(), and .val() which act as getters, retrieving
information from DOM elements for later use.
As a web developer, the frequently need to manipulate the DOM, the object model that is
used by browsers to specify the logical structure of web pages, and based on this structure
to render HTML elements on the screen. HTML defines the default DOM structure. In many
cases it may want to manipulate this with JavaScript, usually in order to add extra functionalities
to a site.

Elements provide a range of DOM- methods to find elements, and extract and manipulate
their data. The DOM getters are contextual: called on a parent Document they find matching
elements under the document; called on a child element they find elements under that child.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 21


Finding elements:
 getElementById(String id)
 getElementsByTag(String tag)
 getElementsByClass(String className)
 getElementsByAttribute(String key) (and related methods)
 Element
siblings: siblingElements(), firstElementSibling(), lastElementSibling(); nextElementSibling(), 
previousElementSibling()
 Graph: parent(), children(), child(int index)

Element data:
 attr(String key) to get and attr(String key, String value) to set attributes
 attributes() to get all attributes
 id(), className() and classNames()
 text() to get and text(String value) to set the text content
 html() to get and html(String value) to set the inner HTML content
 outerHtml() to get the outer HTML value
 data() to get data content (e.g. of script and style tags)
 tag() and tagName()

Manipulating HTML and text:


 append(String html), prepend(String html)
 appendText(String text), prependText(String text)
 appendElement(String tagName), prependElement(String tagName)
 html(String value)

1. Content Manipulation: The html( ) method gets the html contents (inner HTML) of the
first matched element.
Syntax: selector.html( )
Example: The Following example which makes use of .html() and .text(val) methods. Here .html()
retrieves HTML content from the object and then .text( val ) method sets value of the object using
passed parameter:
<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() {
$("div").click(function () {
var content = $(this).html();
$("#result").text( content );
}); });
</script>
<style>
#division{ margin:10px;padding:12px;
border:2px solid #666;
width:60px;
} </style> </head>

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 22


<body>
<p>Click on the square below:</p>
<span id="result"> </span>
<div id="division" style="background-color:blue;">
This is Blue Square!!
</div> </body> </html>
Result: Click on the square below:
Click Here

2. DOM Element Replacement:


It can replace a complete DOM element with the specified HTML or DOM elements. The
replaceWith( content ) method serves very well.
Syntax : selector.replaceWith( content )
The content is instead of original element. This could be HTML or simple text.
Example:
<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()
{
$("div").click(function ()
{
$(this).replaceWith("<h1>JQuery is Great</h1>");
}); });
</script>
<style>
#division{ margin:10px;padding:12px;
border:2px solid #666;
width:60px;
}
</style> </head>
<body>
<p>Click on the square below:</p>
<span id="result"> </span>
<div id="division" style="background-color:blue;"> This is Blue Square!!
</div> </body> </html>
3. Inserting DOM Elements: To insert new one or more DOM elements in existing document.
JQuery provides various methods to insert elements at various locations.
The Inserting methods are:
1. After( content )
2. Before( content )
The after( content ) method insert content after each of the matched elements where as the
before( content ) method inserts content before each of the matched elements.
Syntax :
selector.after( content );
or
selector.before( content )

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 23


4. Removing DOM Elements: To remove one or more DOM elements from the document.
JQuery provides two methods to handle the situation.
The Removing Dom methods are:
1. Empty ()
2. Remove( content )
The empty( ) method remove all child nodes from the set of matched elements whereas the
remove( expr ) method removes all matched elements from the DOM.
Syntax : selector.remove( [ expr ])
or
selector.empty( )
Example:
<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() {
$("div").click(function () {
$(this).before('<div class="div"></div>' );
}); });
</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 class="div" style="background-color:blue;"></div>
<div class="div" style="background-color:green;"></div>
<div class="div" style="background-color:red;"></div>
</body> </html>
Result:

6. DOM Manipulation Methods:


The Following table lists down all the methods which can use to manipulate DOM elements:
Method Description
1. after( content ) : Insert content after each of the matched elements.
2. append( content ) : Append content to the inside of every matched element.
3 appendTo( selector ) : Append all of the matched elements to another, set of elements.
4 before( content ): Insert content before each of the matched elements.
5 clone( bool ): Clone matched DOM Elements, all their event handlers, and select the clones.
6 clone( ): Clone matched DOM Elements and select the clones.
7 empty( ): Remove all child nodes from the set of matched elements.
8 html( val ) : Set the html contents of every matched element.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 24


9 html( ): Get the html contents (innerHTML) of the first matched element.
10 insertAfter( selector ): Insert all of the matched elements after another, set of elements.
11 insertBefore( selector ): Insert all of the matched elements before another, set of elements.
12 prepend( content ): Prepend content to the inside of every matched element.
13 prependTo( selector ): Prepend all of the matched elements to another, set of elements.
14 remove( expr ) Removes all matched elements from the DOM.
15 replaceAll( selector ):elements matched by the specified selector with the matched elements.
16 replaceWith( content ): Replaces all matched elements with the HTML or DOM elements.
17 text( val ): Set the text contents of all matched elements.
18 text( ): Get the combined text contents of all matched elements.
19 wrap( elem ) Wrap each matched element with the specified element.
20 wrap( html ) Wrap each matched element with the specified HTML content.
21 wrapAll( elem ) Wrap all the elements in the matched set into a single wrapper element.
22 wrapAll( html ) Wrap all the elements in the matched set into a single wrapper element.
23 wrapInner( elem ): inner child contents of each matched element with a DOM element.

Example: <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() {
$("div").click(function () {
var content = 'div class="div"';
$("#destination").wrap(document.createElement(content));
}); });
</script>
<style>
.div{ margin:10px;padding:12px;
border:2px solid #666;
width:60px;
}
</style> </head>
<body>
<p>Click on any square below to see the result:</p>
<div class="div" id="destination">THIS IS TEST</div>
<div class="div" style="background-color:blue;">ONE</div>
<div class="div" style="background-color:green;">TWO</div>
<div class="div" style="background-color:red;">THREE</div>
</body> </html>

Results : Click on any square below to see the result:


ONE

TWO

THREE

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 25


JQuery Event Handling
Q). Explain about jquery event handling with examples?

The ability to create dynamic web pages by using events. Events are actions that can be
defined in the Web Applications. An event represents the precise moment when something
happens.

 moving a mouse over an element


 selecting a radio button
 clicking on an element
For examples events:
 A mouse click
 A web page loading
 Taking mouse over an element
 Submitting an HTML form
 A keystroke on your keyboard, etc.
When these events are triggered, then use a custom function to do much whatever you
want with the event. These custom functions call Event Handlers.
selector.bind( eventType[, eventData], handler)
OR
$("p").click(function(){
  // action goes here!!
});
Commonly Used jQuery Event Methods:
Event Methods Description
1. click() : The click() method attaches an event handler function to an HTML element.
2. dblclick(): The dblclick() method attaches an event handler function to an HTML element.
3. mouseenter(): The method attaches an event handler function to an HTML element.
4. mouseleave(): The method attaches an event handler function to an HTML element.
5. mousedown(): The method attaches an event handler function to an HTML element.
6. mouseup(): attaches an event handler function to an HTML element.
7. blur(): The method attaches an event handler function to an HTML form field.
8. focus(): The method attaches an event handler function to an HTML form field.
9. on(): The method attaches one or more event handlers for the selected elements.
The Type of event handling methods are performed to some basic concepts are:
1. Binding Event handling
2. Removing Event Handling
3. Event Objects.
4. Triggering events
1. Binding Event Handling:
Using the jQuery Event Model, we can establish event handlers on DOM elements with the
bind() method as follows:
Sysntax:
selector.bind( eventType[, eventData], handler)
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 26
The following parameters are:
EventType: A string containing a JavaScript event type, such as click or submit buttons and
refers to the next section for a complete list of event types.
EventData: This parameter is a map of data that will be passed to the event handler.
Handler: A function to execute each time the event is triggered.

A binding event

Example : <html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('div').bind('click', function( event ){
alert('Hi there!');
}); });
</script> <style>
.div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
</style> </head>
<body>
<p>Click on any square below to see the result:</p>
<div class="div" style="background-color:blue;">ONE</div>
<div class="div" style="background-color:green;">TWO</div>
<div class="div" style="background-color:red;">THREE</div>
</body> </html>
Result: This code will cause the division element to respond to the click event; when a user clicks
inside this division thereafter, the alert will be shown.

ONE

TWO

THREE

2. Removing Event Handlers:


Once an event handler is established, it remains in effect for the life of the page. There may
be a need, when to remove event handler. jQuery provides the unbind() command to remove an
exiting event handler.
Syntax :
selector.unbind(eventType, handler)
or
selector.unbind(eventType)
Following parameters re:
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 27
eventType: A string containing a JavaScript event type, such as click or submit. Refer to the next
section for a complete list of event types.
handler: If provided, identifies the specific listener that’s to be removed.

3. The Event Object:


The callback function takes a single parameter; when the handler is called the JavaScript
event object will be passed through it. The event object is often unnecessary and the parameter is
omitted, as sufficient context is usually available when the handler is bound to exactly what needs
to be done when the handler is triggered, however there are certain attributes which you would
need to be accessed.
4. Event Attributes: The following event properties/attributes are available and safe to access
in a platform independent manner:
Event Attributes Description
1 altKey Set to true if the Alt key was pressed when the event was triggered, false if
not.
2 ctrlKey Set to true if the Ctrl key was pressed when the event was triggered, false if
not.
3 data if any, passed as the second parameter to the bind() command when the
handler was established.
4 keyCode For keyup and keydown events, this returns the key that was pressed.
5 metaKey The Meta key is the Ctrl key on PCs and the Command key on Macs.
6 pageX For mouse events, specifies the horizontal coordinate of the event relative
from the page origin.
7 pageY For mouse events, specifies the vertical coordinate of the event relative from
the page origin.
8 screenX specifies the horizontal coordinate of the event relative from the screen
origin.
9 screenY specifies the horizontal coordinate of the event relative from the screen
origin.
10 target Identifies the element for which the event was triggered.
12 Timestamp The timestamp (in milliseconds) when the event was created.
13 type For all events, specifies the type of event that was triggered .

Example:
<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() {
function aClick() {
$("div").show().fadeOut("slow");
}
$("#bind").click(function () {
$("#theone").click(aClick)
.text("Can Click!");
});
$("#unbind").click(function () {
$("#theone").unbind('click', aClick)
.text("Does nothing...");

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 28


}); });
</script> <style>
button { margin:5px; }
button#theone { color:red; background:yellow; }
</style> </head>
<body>
<button id="theone">Does nothing...</button>
<button id="bind">Bind Click</button>
<button id="unbind">Unbind Click</button>
<div style="display:none;">Click!</div>
</body>
</html>
Result:
Click on any square below to see the result:

JQuery Effects:
Q). Explain about JQuery Effects with examples?
jQuery provides a simple interface for doing different kind of amazing effects. jQuery
methods allow us to quickly apply commonly used effects with a minimum configuration.
To create dynamic web pages by using events. Events are actions that can be detected in
Web Application. The Following examples events are:
 A mouse click
 A web page loading
 Taking mouse over an element
 Submitting an HTML form
 A keystroke on your keyboard, etc.
When these events are triggered, then use a custom function to do whatever you want with the
event. These custom functions call Event Handlers and to covers all the important jQuery
methods to create visual effects.

Syntax: [selector].show( speed, [callback] );

jQuery enables to add effects on a web page. Jquery effects are used to perform the special events
are :

 Showing
 Hiding
 Fading
 Sliding
 animation effects.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 29


1. Showing and Hiding Elements:
The commands for showing and hiding elements are much what we can expect
− show() to show the elements in a wrapped set and hide() to hide them.

Syntax for show() method :
[selector].show( speed, [callback] );

JQuery effect methods are used to create events by using speed and callback parameters. The
description of all the parameters:

 speed − A string representing one of the three predefined speeds ("slow", "normal", or
"fast") or the number of milliseconds to run the animation (e.g. 1000).

 callback − This optional parameter represents a function to be executed whenever the


animation completes; executes once for each element animated against.

Syntax for hide() method: [selector].hide( speed, [callback] );

2. Toggling the Elements:


jQuery provides methods to toggle the display state of elements between shown or hidden.
If the element is initially displayed, it will be hidden; if hidden, it will be shown.

Syntax: [selector]..toggle( [speed], [callback] );

3. JQuery -Effect Methods:


The basic concept of jQuery Effects are Following all the important methods to create different
kind of effects:
Effect Methods and Description
1. animate( params, [duration, easing, callback] ) : A function for making custom
animations
2. show( ) : Displays each of the set of matched elements if they are hidden.
3. show( speed, [callback] ) :Show all matched elements using a animation and callback
after completion.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 30


4. hide( ): Hides each of the set of matched elements if they are shown.
5. hide( speed, [callback] ): Hide all matched elements using a graceful animation
6. slideDown( speed, [callback] ) : All matched elements by adjusting their height.
7. slideToggle( speed, [callback] ): Toggle the visibility of all matched elements by adjusting
their height and callback after completion.
8. slideUp( speed, [callback] ): Hide all matched elements by adjusting their height.
9. fadeIn( speed, [callback] ): Fade in all matched elements by adjusting their opacity.
9. fadeTo( speed, opacity, callback ): Fade the opacity of all matched elements to a specified
opacity
10. fadeOut( speed, [callback] ) : Fade out all matched elements by adjusting their opacity
to 0, then setting display to "none"
11. toggle( speed, [callback] ): Toggle displaying each of the set of matched elements using a
graceful animation and optional callback after completion.
12. toggle( switch ): Toggle displaying each of the set of matched elements based upon the
switch (true shows all elements, false hides all elements).
13. stop( [clearQueue, gotoEnd ]): Stops all the currently running animations on all the
specified elements.
14. jQuery.fx.off: Globally disable all animations.
Example:

<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() {
$("#show").click(function () {
$(".mydiv").show( 1000 );
});
$("#hide").click(function () {
$(".mydiv").hide( 1000 );
}); });
</script>
<style>
.mydiv{
margin:10px;
padding:12px;
border:2px solid #666;
width:100px;
height:100px;
}
</style> </head>
<body>
<div class = "mydiv">
This is a SQUARE
</div>
<input id = "hide" type = "button" value = "Hide" />
<input id = "show" type = "button" value = "Show" />
</body>
</html>

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 31


Result: This is a
SQUARE

SHOW HIDE

Example:

<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() {
$(".clickme").click(function(event){
$(".target").toggle('slow', function(){
$(".log").text('Transition Complete');
});
});
});
</script>
<style>
.clickme{
margin:10px;
padding:12px;
border:2px solid #666;
width:100px;
height:50px;
}
</style> </head>
<body>
<div class = "content">
<div class = "clickme">Click Me</div>
<div class = "target">
<img src = "./images/jquery.jpg" alt = "jQuery" />
</div>
<div class = "log"></div>
</div>
</body>
</html>

Result:

Click Here

SHOW HIDE

JQuery Fade:
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 32
Q). What is a Jquery Fade? And Explain?

The jQuery fadeIn() method is used to fade in a hidden element. The optional callback
parameter is a function to be executed after the fading completes. Like other jQuery effects
methods, optionally specify the duration or speed parameter for
the slideUp() and slideDown() methods to control, how long the slide animation will run(executed).
Durations can be specified either using one of the predefined string 'slow' or 'fast', or in a number
of milliseconds; higher values indicate slower animations.
jQuery Fading Methods: With jQuery can be fade an element in and out of visibility. jQuery has the
following fade methods:

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

1. FadeIn(): The jQuery fadeIn() method is used to fade in a hidden element.

Syntax: $(selector).fadeIn(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following
values: "slow", "fast", or milliseconds.
The optional callback parameter is a function to be executed after the fading completes.
Example: $("button").click(function(){
$("#div1").fadeIn();   $("#div2").fadeIn("slow"); $
("#div3").fadeIn(3000); });
2. FadeOut(): The jQuery fadeOut() method is used to fade out a visible element.
Syntax: $(selector).fadeOut(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values:
"slow", "fast", or milliseconds.
The optional callback parameter is a function to be executed after the fading completes.
Example: $("button").click(function(){
    $("#div1").fadeOut();
    $("#div2").fadeOut("slow"); $("#div3").fadeOut(3000); });
3. FadeToggel(): The jQuery fadeToggle() method toggles between the fadeIn() and fadeOut()
methods.
If the elements are faded out, fadeToggle() will fade them in.
If the elements are faded in, fadeToggle() will fade them out.
Syntax:
$(selector).fadeToggle(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values:
"slow", "fast", or milliseconds.
The optional callback parameter is a function to be executed after the fading completes.
Example: $("button").click(function(){
    $("#div1").fadeToggle();   $("#div2").fadeToggle("slow");
    $("#div3").fadeToggle(3000); });

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 33


4. fadeTo(): The jQuery fadeTo() method allows fading to given opacity (value between 0 and 1).

Syntax: $(selector).fadeTo(speed,opacity,callback);
The required speed parameter specifies the duration of the effect. It can take the following values:
"slow", "fast", or milliseconds. The required opacity parameter in the fadeTo() method specifies
fading to a given opacity (value between 0 and 1).
The optional callback parameter is a function to be executed after the function completes.

Example : $("button").click(function(){
    $("#div1").fadeTo("slow", 0.15);
    $("#div2").fadeTo("slow", 0.4);
    $("#div3").fadeTo("slow", 0.7);
});

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 34


UNIT - III
JQuery -USER INTERFACE
Introduction:

JqueryUI is the most popular front end frameworks currently. It is sleek, intuitive, and
powerful mobile first front-end framework for faster and easier web development. It uses HTML,
CSS and Javascript. which we can use to create complex web applications GUI with ease. It is
divided into sections such as JqueryUI Basic Structure, JqueryUI CSS, JqueryUI Layout
Components and JqueryUI Plugins. Each of these sections contain related topics with simple and
useful examples.

jQueryUI stands for jQuery User Interface. It is a collection of animated visual effects, GUI
widgets, and themes implemented with jQuery, CSS, HTML and JavaScript. These new plug-ins add
a lot of new functionalities in the jQuery core library.

It is a very popular and powerful mobile first front-end framework used for faster and
easier web development. According to a survey it is used on over 176000 websites, making it the
second most popular JavaScript library on the Web.

jQuery UI History: jQueryUI is a free and open source software first published and released in
September 2007. It is distributed by jQuery foundation under the MIT license.

Jquery version no Jquery dependency Release date


1.5 ------- Jun 8, 2008
1.6 1.2.6 Apr 16, 2009
1.7 1.3.2+ Mar 3, 2009
1.8 1.3.2+ Mar 18, 2010
1.11.0-beta.1 1.6+ Apr 25, 2014
1.11.0-beta.2 1.6+ May 23, 2014
1.11.0 1.6+ Jun 26, 2014
1.11.1 1.6+ Aug 13, 2014
1.11.2 1.6+ Oct 16, 2014
1.11.3 1.6+ Feb 12, 2015
Jquery UI Features:
Q). What is a JQuery UI? What are the Features and Benefits of Jquery UI?

jQuery UI stands for jQuery User Interface. It is a collection of animated visual effects, GUI
widgets, and themes implemented with jQuery, CSS, HTML and JavaScript. These new plug-ins add
a lot of new functionalities in the jQuery core library. It is a very popular and powerful mobile first
front-end framework used for faster and easier web development. Jquery UI is categorized into four groups
are :

1. Interactions
2. Widgets
3. Effects
4. Utilities.
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 35
The structure of the library is as shown in the image below :

 Interactions − Interactions are the set of plug-ins which facilitates interactive plugins like
drag, drop, resize and more which give the user to interact with DOM elements.
 Draggable
 Droppable
 Resizable
 Selectable
 Sortable
 Widgets − Widgets are the jQuery plug-ins which makes you able to create user interface
elements like accordian, date picker etc.
 Accordion
 Autocomplete
 Dialog
 Button
 Date Picker
 Menu
 Progress Bar
 Tabs
 Tooltip
 Slider
 Spinner
 Effects The internal jQuery effects contain a full suite of custom animation and transition
for DOM elements.

 Hide
 Show
 Add Class
 Remove Class
 Switch Class
 Toggle Class
 Color Animation
 Effect
 Toggle

 Utilities − These are a set of modular tools the JqueryUI library uses internally.
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 36
Position: It is used to set the position of the element according to the other
element's alignment (position).

Benefits of JqueryUI : The below are some of the benefits of Jquery UI:

I. Cohesive and Consistent APIs.


II. Comprehensive Browser Support.
III. Open Source and Free to Use.
IV. Good Documentation.
V. Powerful Theming Mechanism.
VI. Stable and Maintenance Friendly.

Q). Explain about Jquery UI Interaction methods?


Interactions − Interactions are the set of plug-ins which facilitates interactive plugins like drag,
drop, resize and more which give the user to interact with DOM elements.
1. Draggable
2. Droppable
3. Resizable
4. Selectable
5. Sortable
1. Draggable: jQueryUI provides draggable() method to make any DOM element draggable. Once
the element is draggable, we can move that element by clicking on it with the mouse and dragging
it anywhere within the viewport.
Syntax: The draggable() method can be used in two forms:

1. $(selector, context).draggable (options);


2. $(selector, context).draggable ("action", [params]) ;

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.
Method Action & Description
destroy() Remove drag functionality completely. The elements are
no longer movable. It returns element back to its pre-init
state.
disable() Disable drag functionality. Elements cannot be moved
until the next call to the draggable("enable") method.
enable() Reactivates drag management and it can be moved again.
option(optionName Sets the value of the draggable option associated with the
, value) specified optionName. Where optionName is the name of
the option to set and value is the value to set for the
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 37
option.
Example:

<!DOCTYPE html>
<html>
<head>
<link href = https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<div id = "div6" style = "border:solid 1px;background:#eee; height:50px;">
<span>You can duplicate me....</span>
</div>
<script>
$("#div6 span").draggable ({
helper : "clone"
});
</script> </body> </html>

2. Droppable: jQueryUI provides droppable() method to make any DOM element droppable at a


specified target (a target for draggable elements). The droppable() method can be used in two
forms:

 $(selector, context).droppable (options) Method


 $(selector, context).droppable ("action", params) Method

The droppable (options) method declares that an HTML element can be used as an element in


which we can drop other elements.

Syntax :
1. $(selector, context).droppable (options);
2. $(selector, context).droppable({option1: value1, option2: value2..... });

Method Action & Description


accept It is used when we need to control which draggable elements are to be
accepted for dropping. By default its value is *.
activeClass It is a String representing one or more CSS classes to be added to the
droppable element when an accepted element.By default its value is false.
addClasses when set to false will prevent the ui-droppable class from being added to
the droppable elements. By default its value is true.
disabled when set to true disables the droppable. By default its value is false.
scope It is used to restrict the droppable action of draggable elements only to
items that have the same options.scope . By default its value is "default".

Example:

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 38


<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Droppable - Default functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<style>
#draggable-1 {
width: 100px; height: 50px; padding: 0.5em; float: left;
margin: 22px 5px 10px 0;
}
#droppable-1 {
width: 120px; height: 90px;padding: 0.5em; float: left;
margin: 10px;
} </style>
<script>
$(function() {
$( "#draggable-1" ).draggable();
$( "#droppable-1" ).droppable();
});
</script> </head>
<body>
<div id = "draggable-1" class = "ui-widget-content">
<p>Drag me to my target</p>
</div>
<div id = "droppable-1" class = "ui-widget-header">
<p>Drop here</p>
</div>
</body>
</html>

3. Resizeble: jQueryUI provides resizable() method to resize any DOM element. This method
simplifies the resizing of element which otherwise takes time and lot of coding in HTML. The
resizable () method displays an icon in the bottom right of the item to resize.
$ (selector, context).resizable (options) Method
The resizable (options) method declares that an HTML element can be resized.
The options parameter is an object that specifies the behavior of the elements involved when
resizing.

Syntax:
1. $(selector, context).resizable (options);

2. $(selector, context).resizable({option1: value1, option2: value2..... });

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 39


S.No
Option & Description
.

alsoResize:This option is of type Selector, jQuery , or any DOM Element. It


1 represents elements that also resize when resizing the original object. By default its
value is false.

animate :This option when set to true is used to enable a visual effect during
2
resizing when the mouse button is released. The default value is false (no effect).

animateDuration: This option is used to set the duration (in milliseconds) of the
3 resizing effect. This option is used only when animate option is true. By default its
value is "slow".

animateEasing: This option is used to specify which easing to apply when using


4
the animate option. By default its value is "swing".

aspectRatio:This option is used to indicate whether to keep the aspect (height and
5
width) ratio for the item. By default its value is false.

autoHide: This option is used to hide the magnification icon or handles, except
6
when the mouse is over the item. By default its value is false.

cancel: This option is used to prevent resizing on specified elements. By default its
7
value is input, text area, button, select, option.

containment: This option is used restrict the resizing of elements within a


8
specified element or region. By default its value is false.

delay: This option is used to set tolerance or delay in milliseconds. Resizing or


9
displacement will begin thereafter. By default its value is 0.

disabled: This option disables the resizing mechanism when set to true. The mouse
10 no longer resizes elements, until the mechanism is enabled, using the resizable
("enable"). By default its value is false.

distance: With this option, the resizing starts only when the mouse moves a
11 distance(pixels). By default its value is 1 pixel. This can help prevent unintended
resizing when clicking on an element.

ghost: This option when set to true, a semi-transparent helper element is shown
12 for resizing. This ghost item will be deleted when the mouse is released. By default
its value is false.

grid: This option is of type Array [x, y], indicating the number of pixels that the
13 element expands horizontally and vertically during movement of the mouse. By
default its value is false.

14 handles:This option is a character string indicating which sides or angles of the

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 40


element can be resized. By default its values are e, s, se.

maxHeight:This option is used to set the maximum height the resizable should be
15
allowed to resize to. By default its value is null.

maxWidth: This option is used to set the maximum width the resizable should be
16
allowed to resize to. By default its value is null.

minHeight: This option is used to set the minimum height the resizable should be
17
allowed to resize to. By default its value is 10.

minWidth: This option is used to set the minimum width the resizable should be
18
allowed to resize to. By default its value is 10.

4. Selectable: jQueryUI provides selectable() method to select DOM element individually or in a


group. With this method elements can be selected by dragging a box (sometimes called a lasso)
with the mouse over the elements. Also, elements can be selected by clicking or dragging while
holding the Ctrl/Meta key, allowing for multiple (non-contiguous) selections.

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


The selectable (options) method declares that an HTML element contains selectable items.
The options parameter is an object that specifies the behavior of the elements involved when
selecting.

Syntax:
1. $(selector, context).selectable (options);

2. $(selector, context).selectable({option1: value1, option2: value2..... });

S.No Option & Description


.

appendTo:This option is tells which element the selection helper (the lasso) should
1
be appended to. By default its value is body.

autoRefresh: if set to true, the position and size of each selectable item is computed
2
at the beginning of a select operation. By default its value is true.

cancel: selecting if you start selection of elements. By default its value


3
is input,textarea,button,select,option.

delay: This option is used to set time in milliseconds and defines when the selecting
4
should start. This can be used to prevent unwanted selections. By default its value is 0.

5 disabled: when set to true, disables the selection mechanism. Users cannot select the
elements until the mechanism is restored using the selectable ("enable") instruction.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 41


By default its value is false.

distance: the distance (in pixels) the mouse must move to consider the selection in
6 progress. This is useful, for example, to prevent simple clicks from being interpreted
as a group selection. By default its value is 0.

filter: selector indicating which elements can be part of the selection. By default its
7
value is *.

tolerance: specifies which mode to use for testing whether the selection helper (the
8
lasso) should select an item. By default its value is touch.

5. Sortable: jQueryUI provides sortable() method to reorder elements in list or grid using the


mouse. This method performs sortability action based upon an operation string passed as the
first parameter. $ (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.

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

S.No Option & Description


.

appendTo: This option specifies the element in which the new element created
1 with options.helper will be inserted during the time of the move/drag. By default its
value is parent.

axis: This option indicates an axis of movement ("x" is horizontal, "y" is vertical). By
2
default its value is false.

cancel: This option is used to prevent sorting of elements by clicking on any of the
3
selector elements. By default its value is "input,textarea,button,select,option".

connectWith: This option is a Selector that identifies another sortable element that
4
can accept items from this sortable. By default its value is false.

containment: This option indicates an element within which the displacement takes
place. The element will be represented by a selector (only the first item in the list will
5
be considered), a DOM element, or the string "parent" (parent element) or "window"
(HTML page).

6 cursor: Specifies the cursor CSS property when the element moves. It represents the

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 42


shape of the mouse pointer. By default its value is "auto".

cursorAt: Sets the offset of the dragging helper relative to the mouse cursor.
7 Coordinates can be given as a hash using a combination of one or two keys: { top, left,
right, bottom }. By default its value is "false".

delay: Delay, in milliseconds, after which the first movement of the mouse is taken
8
into account. The displacement may begin after that time. By default its value is "0".

disabled: This option if set to true, disables the sortable functionality. By default its
9
value is false.

distance: Number of pixels that the mouse must be moved before the sorting starts. If
10 specified, sorting will not start until after mouse is dragged beyond distance. By
default its value is "1".

dropOnEmpty:This option if set to false, then items from this sortable can't be
11
dropped on an empty connect sortable. By default its value is true.

scrollSpeed: This option indicates the scrolling speed of the display once the scrolling
12 begins. By default its value is 20.

zIndex: This option represents z-index for element/helper while being sorted. By
13
default its value is 1000.

Q). Explain about Jquery UI Widgeds methods with examples?


Widgets − Widgets are the jQuery plug-ins which makes you able to create user interface
elements like accordian, date picker etc.
1. Accordion
2. Autocomplete
3. Dialog
4. Button
5. Date Picker
6. Menu
7. Progress Bar
8. Tabs
9. Tooltip
10. Slider
11. Spinner

1. Accordion: Accordion Widget in jQueryUI is a jQuery based expandable and collapsible


content holder that is broken into sections and probably looks like tabs. jQueryUI provides
accordion() method to achieve. $ (selector, context).accordion (options) Method

The accordion (options) method declares that an HTML element and its contents should be
treated and managed as accordion menus. The options parameter is an object that specifies the
appearance and behavior of the menu involved.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 43


Syntax:
1. $(selector, context).accordion (options);

2. $(selector, context).accordion({option1: value1, option2: value2..... });

S.No Option & Description


.

active :Indicates the index of the menu that is open when the page is first accessed. By
1
default its value is 0, i.e the first menu.

animate: This option is used to set how to animate changing panels. By default its
2
value is {}.

collapsible: This option when set to true, it allows users to close a menu by clicking
3 on it. By default, clicks on the open panel’s header have no effect. By default its value
is false.

disabled: This option when set to true disables the accordion. By default its value
4
is false.

event: This option specifies the event used to select an accordion header. By default
5
its value is click.

2. AutoComplete : Auto completion is a mechanism frequently used in modern websites to


provide the user with a list of suggestions for the beginning of the word, which he/she has typed
in a text box. The user can then select an item from the list, which will be displayed in the input
field. This feature prevents the user from having to enter an entire word or a set of words.

JQueryUI provides an autocomplete widget — a control that acts a lot like a <select>
dropdown, but filters the choices to present only those that match what the user is typing into a
control. jQueryUI provides the autocomplete()method to create a list of suggestions below the
input field and adds new CSS classes to the elements concerned to give the appropriate style.
Any field that can receive input can be converted into an Autocomplete,
namely, <input> elements, <textarea> elements, and elements with the contenteditableattribute.
Syntax: $(selector, context).autocomplete (options);
1. $(selector, context).autocomplete ("action", params) ;

The following table lists the different options that can be used with this method :

S.No Option & Description


.

1 appendTo: This option is used append an element to the menu. By default its value

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 44


is null.

autoFocus: This option when set to true, the first item of the menu will automatically
2
be focused when the menu is shown. By default its value is false.

minLength: The number of characters that must be entered before trying to obtain
3 the matching values (as specified by the source option). This can prevent too large a
value set from being presented.

3. Buttons: jQueryUI provides button() method to transform the HTML elements (like buttons,
inputs and anchors) into themeable buttons, with automatic management of mouse movements
on them, all managed transparently by jQuery UI.

In order to group radio buttons, Button also provides an additional widget,


called Buttonset. Buttonset is used by selecting a container element (which contains the radio
buttons) and calling .buttonset(). $ (selector, context).button (options) Method

Syntax:
1. $(selector, context).button (options);

2. $(selector, context).button({option1: value1, option2: value2..... });

The following table lists the different options that can be used with this method :

Sr.No Option & Description


.

disabled: This option deactivates the button is set to true. By default its value
1
is false.

icons: y7This option specifies that one or two icons are to be displayed in the button:
2 primary icons to the left, secondary icons to the right. By default its value is primary:
null, secondary: null.

label: This option specifies text to display on the button that overrides the natural
3 label. If omitted, the natural label for the element is displayed. By default its value
is null.

text: This option specifies whether text is to be displayed on the button. If specified
4 as false, text is suppressed if (and only if) the icons option specifies at least one icon.
By default its value is true.

4. Dialog: Dialog boxes are one of the nice ways of presenting information on an HTML page. A
dialog box is a floating window with a title and content area. This window can be moved, resized,
and of course, closed using "X" icon by default.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 45


jQueryUI provides dialog() method that transforms the HTML code written on the page into
HTML code to display a dialog box.

Syntax:
1. $(selector, context).dialog (options);
2. $(selector, context).dialog ("action", [params]);

The following table lists the different options that can be used with this method:

resizable: This option unless set to false, the dialog box is resizable in all directions. By
1
default its value is true.

show: This option is an effect to be used when the dialog box is being opened. By default
2
its value is null.

title: This option specifies the text to appear in the title bar of the dialog box. By default
3
its value is null.

width: This option specifies the width of the dialog box in pixels. By default its value
4
is 300.

5. DatePickers: Datepickers in jQueryUI allow users to enter dates easily and visually. We can
customize the date format and language, restrict the selectable date ranges and add in buttons
and other navigation options easily.

jQueryUI provides datepicker() method that creates a datepicker and changes the appearance of


HTML elements on a page by adding new CSS classes. Transforms the <input>, <div>, and <span>
elements in the wrapped set into a datepicker control.
By default, for <input> elements, the datepicker calendar opens in a small overlay when the
associated text field gains focus. For an inline calendar, simply attach the datepicker to a <div>, or
<span> element.
$ (selector, context).datepicker (options) Method
The datepicker (options) method declares that an <input> element (or <div>, or <span>,
depending on how you choose to display the calendar) should be managed as a datepicker.
The options parameter is an object that specifies the behavior and appearance of the datepicker
elements.
Syntax:
1. $(selector, context).datepicker(options);

2. $(selector, context).datepicker({option1: value1, option2: value2..... });

The following table lists the different options that can be used with this method −

1 altFormat: This option is used when an altField option is specified. It provides the format

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 46


for the value to be written to the alternate element. By default its value is "".

appendText: This option is a String value to be placed after the <input> element,
2
intended to show instructions to the user. By default its value is "".

autoSize: This option when set to true resizes the <input> element to accommodate the
3
datepicker’s date format as set with the dateFormat option. By default its value is false.

beforeShow: This option is a callback function that’s invoked just before a datepicker is
4 displayed, with the <input> element and datepicker instance passed as parameters. By
default its value is "".

beforeShowDay: This option is a callback function which takes a date as parameter, that’s
5 invoked for each day in the datepicker just before it’s displayed, with the date passed as
the only parameter. By default its value is null.

calculateWeek: This option is a custom function to calculate and return the week number
6 for a date passed as the lone parameter. The default implementation is that provided by
the $.datepicker.iso8601Week()utility function.

changeMonth: This option if set to true, a month dropdown is displayed, allowing the
7 user to directly change the month without using the arrow buttons to step through them.
By default its value is false.

changeYear: This option if set to true, a year dropdown is displayed, allowing the user to
directly change the year without using the arrow buttons to step through them.
8
Option yearRange can be used to control which years are made available for selection. By
default its value is false.

closeText: This option specifies the text to replace the default caption of Done for the
9 close button. It is used when the button panel is displayed via
the showButtonPanel option. By default its value is "Done".

6. Menu: The jQuery UI Menu widget consists of a main menu bar with pop up menus. Some
items in the pop up menus also have sub pop up menus. These menus are created by using
markup elements as long as the parent child relationship is maintained. The jQuery UI uses the
menu() method to create menus.

Syntax: 1. $(selector, context).menu (options);  
2. $(selector, context).menu({option1: value1, option2: value2..... });  

Following is a list of different options that can be used with this method.
Option Description

disable If set option to true, it disables the menu. By default its value is false.
d

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 47


icons This option sets the icons for submenus. By default its value is { submenu: "ui-icon-
carat-1-e" }.

menus This option is a selector for the elements that serve as the menu container, including
sub-menus. By default its value is ul.

positio sets the position of submenus in relation to the associated parent menu item. By
n default its value is { my: "left top", at: "right top" }.

role This option is used to customize the aria roles used for the menu and menu items. By
default its value is menu.

7. Progress bar: Progress bars indicate the completion percentage of an operation or process. We
can categorize progress bar as determinate progress bar and indeterminate progress bar.

Determinate progress bar should only be used in situations where the system can accurately update
the current status. A determinate progress bar should never fill from left to right, then loop back to
empty for a single process.

If the actual status cannot be calculated, an indeterminate progress bar should be used to provide
user feedback.

jQueryUI provides an easy-to-use progress bar widget that we can use to let users know that our
application is hard at work performing the requested operation. jQueryUI provides progressbar()
method to create progress bars. Syntax:

1. $(selector, context).progressbar (options);

2. $(selector, context).progressbar({option1: value1, option2: value2..... });

The following table lists the different options that can be used with this method :

Sr.No. Option & Description

disabled
when set to true disables the progress bars. By default its value is false.

max To sets the maximum value for a progress bar. By default its value is 100.
value :Tospecifies the initial value of the progress bar. By default its value is 0.

8. Spinner: widget adds a up/down arrow to the left of a input box thus allowing a user to
increment/decrement a value in the input box. It allows users to type a value directly, or modify
an existing value by spinning with the keyboard, mouse or scrollwheel. It also has a step feature to
skip values. In addition to the basic numeric features, it also enables globalized formatting options
(ie currency, thousand separator, decimals, etc.) thus providing a convenient internationalized
masked entry box. jQueryUI provides spinner() method which creates a spinner.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 48


Syntax: The spinner() method can be used in two forms:
 $(selector, context).spinner (options):

 $(selector, context).spinner ("action", params) ;

Example: 1
<!doctype html>  
1. <html lang="en">  
2.    <head>  
3.       <meta charset="utf-8">  
4.       <title>jQuery UI ProgressBar functionality</title>  
5.       <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">  
6.       <script src="http://code.jquery.com/jquery-1.10.2.js"></script>  
7.       <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>  
8.       <style>  
9.          .ui-widget-header {               background: blue;  
10.             border: 1px solid #DDDDDD;  
11.             color: #333333;  
12.             font-weight: bold;  
13.          }         </style>         <script>  
14.          $(function() {  
15.             $( "#progressbar-1" ).progressbar({                 value: 30  
16.             });            });  
17.       </script>      </head>  
18.    <body>         <div id="progressbar-1"></div>   
19.    </body>  </html>  
Q). Explain about Jquery UI Effects methods with examples?

Effects The internal jQuery effects contain a full suite of custom animation and transition for DOM
elements.

1. Hide
2. Show
3. Add Class
4. Remove Class
5. Switch Class
6. Toggle Class
7. Color Animation
8. Effect
9. Toggle

1. Hide: the hide() method, which is one of the methods used to manage jQueryUI visual effects.
effect() method applies an animation effect to hide elements.

Syntax: .hide( effect [, options ] [, duration ] [, complete ] )


Sr.No
Parameter & Description
.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 49


1 Effect: This is a String indicating which effect to use for the transition.

Options: This is of type Object and indicates effect-specific settings and easing. Additionally, each
2 effect has its own set of options that can be specified common across multiple effects described in
the table jQueryUI Effects.

Duration : This is of type Number or String, and indicates the number of milliseconds of the effect.
3
Its default value is 400.

Complete: This is a callback method called for each element when the effect is complete for this
4
element.

jQueryUI Effects: The following table describes the various effects that can be used with the hide()
method :
Sr.No
Effect & Description
.

1 Blind: Shows or hides the element in the manner of a window blind: by moving the bottom edge down
or up, or the right edge to the right or left, depending upon the specified direction and mode.

Bounce: Causes the element to appear to bounce in the vertical or horizontal direction, optionally
2
showing or hiding the element.

Clip: Shows or hides the element by moving opposite borders of the element together until they meet in
3
the middle, or vice versa.

4 Drop: Shows or hides the element by making it appear to drop onto, or drop off of, the page.

Explode: Shows or hides the element by splitting it into multiple pieces that move in radial directions as
5
if imploding into, or exploding from, the page.

Fade: Shows or hides the element by adjusting its opacity. This is the same as the core fade effects, but
6
without options.

Fold:Shows or hides the element by adjusting opposite borders in or out, and then doing the same for
7
the other set of borders.

Highlight:Calls attention to the element by momentarily changing its background color while showing
8
or hiding the element.

9 Puff:Expands or contracts the element in place while adjusting its opacity.

10 Pulsate:Adjusts the opacity of the element on and off before ensuring that the element is shown or

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 50


hidden as specified.

11 Scale:Expands or contracts the element by a specified percentage.

12 Shake:Shakes the element back and forth, either vertically or horizontally.

Size:Resizes the element to a specified width and height. Similar to scale except for how the target size is
14
specified.

15 Slide:Moves the element such that it appears to slide onto or off of the page.

Transfer:Animates a transient outline element that makes the element appear to transfer to another
16 element. The appearance of the outline element must be defined via CSS rules for the ui-effects-transfer
class, or the class specified as an option.

2. Show: This chapter will discuss the show() method, which is one of the methods used to
manage jQueryUI visual effects. show() method displays an item using the indicated effect.

show() method toggles the visibility of the wrapped elements using the specified effect.

Syntax:

.show( effect [, options ] [, duration ] [, complete ] )

3. Add Class: the addClass() method, which is one of the methods used to manage jQueryUI
visual effects. addClass() method allow animating the changes to the CSS properties.

addClass() method add specified classes to the matched elements while animating all style
changes.

Syntax: .addClass( className [, duration ] [, easing ] [, complete ] );


4. Remove Class: the removeClass() method, wh ich is one of the methods used to manage
jQueryUI visual effects. removeClass() method removes the applied classes from the elements.

removeClass() method removes the specified classes to the matched elements while animating all
style changes.

Syntax: .removeClass( className [, duration ] [, easing ] [, complete ] )


5. Color Animated: jQueryUI extends some core jQuery methods so that you can animate
different transitions for an element. One of them being animate method. jQueryUI extends the
jQuery animate method, to add support for animating colors. You can animate one of several CSS
properties that define an element’s colors. Following are the CSS properties that
the animate method supports.

 backgroundColor − Sets the background color of the element.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 51


 borderTopColor − Sets the color for top side of the element border.
 borderBottomColor − Sets the color for bottom side of the element border.
 borderLeftColor − Sets the color for left side of the element border.
 borderRightColor − Sets the color for right side of the element border.
 color − Sets the text color of the element.
 outlineColor − Sets the color for the outline; used to emphasize the element.

Syntax: $( "#selector" ).animate(

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

6. Effect: the effect() method, which is one of the methods used to manage jQueryUI visual
effects. effect() method applies an animation effect to the elements without having to show or hide
it.

Syntax: .effect( effect [, options ] [, duration ] [, complete ] )


7.Toggle():the toggle() method of jQueryUI visual effects. toggle() method toggles the show () or
hide () methods depending on whether the element is hidden or not.

Syntax: .toggle( effect [, options ] [, duration ] [, complete ] )


Example:

<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Toggle Example</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- CSS -->
<style>
.toggler { width: 500px; height: 200px; }
#button { padding: .5em 1em; text-decoration: none; }
#effect { width: 240px; height: 135px; padding: 0.4em; position: relative; }
#effect h3 { margin: 0; padding: 0.4em; text-align: center; }
</style>
<script>
$(function() {
function runEffect() {
$( "#effect" ).toggle('explode', 300);
};
$( "#button" ).click(function() {
runEffect();
return false;
});

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 52


});
</script>
</head>
<body>
<div class = "toggler">
<div id = "effect" class = "ui-widget-content ui-corner-all">
<h3 class = "ui-widget-header ui-corner-all">Toggle</h3>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore.
</p>
</div>
</div>
<a href = "#" id = "button" class = "ui-state-default ui-corner-all">Toggle</a>
</body>
</html>
Result:

Toggle

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt
ut labore.

Toggle

Jquery UI Themes
Introduction:
Themes are not a new concept. probably rolled out a using Cascading Style Sheet (CSS)
styles and classes to format the look and feel of a good websites. Using a framework standardizes
the approach and lessens the amount of work and code needing to be written.
jQuery UI is now the industry standard for theme implementation. There are other choices,
such as Dojo (coupled with Dijit) or Ext JS, but jQuery UI combines themes with the use of widgets,
which are the elements with which users interact date pickers or buttons. When dissecting the
inner workings of the files that make up a jQuery UI theme, what you find is nothing more than
CSS and JavaScript. But it's the thought process and standardization that have gone into this use of
CSS and JavaScript that makes jQuery UI such an excellent platform for building the look and feel
of a website.
Q). Explain about Jquery UI Themes with examples?

jQuery UI combines themes with the use of widgets, which are the elements with which
users interact date pickers or buttons. When dissecting the inner workings of the files that make
up a jQuery UI theme.
The jQuery UI platform consists of two sub-frameworks:
1. a widget framework: which contains the Widget Factory and a set of commonly used widgets,
2. CSS framework. The Widget Factory provides the basis for all jQuery UI widgets, including those
common widgets included in the set of widgets.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 53


When creating widgets, use either one of the common widgets from the set as a starting
point or create one from scratch. Once the common widgets are, open any of editor and view the
code, either modify this code and generate a customized widget or create one with a similar
structure.
The jQuery UI themes folder structure:
Before continuing to look at the various files and their contents, download one of the themes from
the jQuery UI platform. The downloaded ZIP file contains three folders: css, js, and development-
bundle. The development-bundle folder contains a folder named themes, which is where jQuery UI
themes under development are kept. The themes folder in turn contains a folder with the name of
the selected/downloaded.
The css folder contains a folder with the name of the theme downloaded. This theme folder
contains a CSS file that incorporates the CSS markup for all of the components or widgets. The
development-bundle folder also contains a themes/[theme-name] folder that contains the
individual CSS files for each component or widget.
This structure makes it easier to find and modify the changes in own themes:

Structure of the themes folder:

The jquery.ui.theme.css file has three different types of styles:


 Container - This style defines the container theme, such as ui-widget, ui-widget-content,
or ui-widget-header.
 States - This style type is used by jQuery UI widgets to define the look of the widget as the
user interacts with it. Classes include ui-state-default, ui-state-hover, and ui-state-active.
 Cues - As something happens in the application (not by the user's action), these classes
change the look of the widget. The classes include ui-state-highlight, ui-state-error, and ui-state-
disabled.

Customise UI widgets:

The three widgets in this application are defined using <div> statements for the most part
(except for the button, which already has a tag in HTML). These widgets are defined in the
following code:

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 54


1 <div id="sld_value" style="margin-bottom:10px;"></div>
2 <button id="btn_value">Display Value</button>
3 <div id="dlg_value"></div>
The tab contains the following important sections (among others):
 Font Settings - Allows general changes to the font used throughout a theme.
 Corner Radius - Controls the rounding (or lack) of corners for various widgets.
 Header/Toolbar - Provides the look and feel for headers used in the various widgets.
 Content - Provides settings to control the main body of the widgets.
 Clickable - Controls various states that the widgets use.

Widget events:

The widgets are fundamentally JavaScript objects, they can be set up with events that fire during
the lifetime of the website application. events fire, they are caught by either your website's
provided JavaScript code or handled within the widgets.

1 $( "#dlg_popup" ).dialog({
2    drag: function(event, ui) { ... }
3 });
Widget methods:

Methods are associated with the widget and allow the execution of pre-written functionality on a
particular widget to have it perform a specific action. an example of calling a widget's method:
1 $(“#dlg_popup”).dialog("moveToTop”);
Switching themes: Code can be included in HTML and JavaScript files that give the ability to
switch themes on the fly using a drop-down menu. the changes to the HTML source code to
make such a change.

Creating unique themes:

Using the ThemeRoller changes can be made to an existing jQuery theme (as a starting
point) to create a unique theme. Doing so eliminates the need to create the theme from scratch. It
also means expertise in CSS isn't required, and the tool allows you to view changes to existing
themes and widgets on the fly. 

The tab contains the following important sections (among others):

 Font Settings - Allows general changes to the font used throughout a theme.
 Corner Radius - Controls the rounding (or lack) of corners for various widgets.
 Header/Toolbar - Provides the look and feel for headers used in the various widgets.
 Content - Provides settings to control the main body of the widgets.
 Clickable - Controls various states that the widgets use.
Example:

The ThemeRoller site:

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 55


Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 56
JQuery Plugins:

Q). What is JQuery Plugins and explain the validation plugins?

A jQuery plugin is simply a new method that we use to extend jQuery's prototype object. By
extending the prototype object, it can be enable all jQuery objects to inherit any methods that you
add. whenever you call jQuery()to creating a new jQuery object, with all of jQuery's methods
inherited.

The idea of a plugin is to do something with a collection of elements. It consider each method that
comes with the jQuery core a plugins such as:

1.  .fadeOut()
2.  .addClass().

It can make own plugins and use them privately in a code or release them into the wild. There are
thousands of jQuery plugins available online.

jQuery Validation Plugin:

jQuery plugin makes simple clientside form validation easy to customization options. It
makes a good choice if you’re building something new from scratch. The plugin comes bundled
with a useful set of validation methods, including URL and email validation, while providing an API
to write own methods. All bundled methods come with default error messages in english and
translations into 37 other languages.

Finding & Evaluating Plugins:


One of the most aspects of jQuery is its extensive plugin ecosystem. From table sorting to
form validation to autocompletion – if there's a need for it, chances are good that someone has
written a plugin for it.

The quality of jQuery plugins varies widely. Many plugins are extensively tested and well-
maintained. Some plugins, mainly jQuery UI, are maintained by the jQuery team. The quality of
these plugins is as good as jQuery itself.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 57


UNIT – IV
AJAX
Q). What is Ajax? And explain?
AJAX is an acronym stands for Asynchronous JavaScript and XML and this technology helps
us to load data from the server without a browser page refresh. JQuery is a great tool which
provides a rich set of AJAX methods to develop next generation web application.
How to AJAX Works:

1. An event occurs in a web page (the page is loaded, a button is clicked)


2. An XMLHttpRequest object is created by JavaScript
3. The XMLHttpRequest object sends a request to a web server
4. The server processes the request
5. The server sends a response back to the web page
6. The response is read by JavaScript
7. Proper action (like page update) is performed by JavaScript

Loading Simple Data

1. Getting JSON data.


Loading Simple Data:
Loading Simple Data This is very easy to load any static or dynamic data using JQuery AJAX.
JQuery provides load() method to do the job:
Syntax :
[selector].load( URL, [data], [callback] );
The description of all the parameters:
URL: The URL of the server-side resource to which the request is sent. It could be a CGI, ASP, JSP,
or PHP script which generates data dynamically or out of a database.
DATA: This optional parameter represents an object whose properties are serialized into properly
encoded parameters to be passed to the request. If specified, the request is made using the POST
method. If omitted or avoid , the GET method is used.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 58


CALLBACK: A callback function invoked after the response data has been loaded into the elements
of the matched set. The first parameter passed to this function is the response text received from
the server and second parameter is the status code.

Example: <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() {
$("#driver").click(function(event){
$('#stage').load('/jquery/result.html');
}); });
</script>
</head>
<body>
<p>Click on the button to load result.html file:</p>
<div id="stage" style="background-color:blue;">
STAGE
</div> <input type="button" id="driver" value="Load Data" />
</body> </html>
Here load() initiates an Ajax request to the specified URL /jquery/result.html file. After loading
this file, all the content would be populated inside <div> tagged with ID stage. Assuming, our
/jquery/result.html file has just one HTML line:
Passing Data to the Server: Many times it collect input from the user and to pass that input to the
server for further processing. JQuery AJAX made it easy enough to pass collected data to the server
using data parameter of any available Ajax method.

Advantages to Ajax:

1. JavaScript is the client-side programming language and XML is a markup language to define


data. 
2. JSON is another markup language to define data. JSON (JavaScript Object Notation) is much
easier to use with JavaScript than XML. When it comes to Ajax and JavaScript, JSON Web
Services are replacing XML Web Services.
3. Another major advance to JavaScript and Ajax is the JavaScript object library called jQuery.
This free, open-source software is a wrapper around JavaScript.
4. jQuery is used to easily write client-side JavaScript to navigate and manipulate a page and
make asynchronous Ajax callbacks.
5. By using jQuery and JSON Web Services, Ajax callbacks have become standard
programming practices for designing and developing web applications.
6. The Ajax Control Toolkit is a suite of controls created by Microsoft that is integrated into
Visual Studio and can be dragged and dropped onto web forms just like html and server
controls.
7. These controls are intended to be used for Ajax callbacks. However, they can also be used
as normal client and or server controls.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 59


For example, Asp.Net does not come with the Tabs controls. However, the Ajax Control Toolkit
does. The Tab control can postback to the server just like server controls.

Q). Where Should be Ajax be Used?

Ajax should be used anywhere in a web application where small amounts of information
could be saved or retrieved from the server without posting back the entire pages.

A good example of this is data validation on save actions. Another example would be to change the
values in a drop down list-box based on other inputs, such as state and college list boxes. When the
user selects a state, the college list box will repopulate with only colleges and universities in that
state. Other features include text hints and autocomplete text boxes. The client types in a couple of
letters and a list of all values that start with those letters appear below.

A callback is made to a web service that will retrieve all values that begin with these characters.
This is a fantastic feature that would be impossible without Ajax and is also part of the Ajax
Control Toolkit.

Segue recently used Ajax to support a client application that had problems due to limited
bandwidth and page size. The combination caused the application to take too long to retrieve data
and display it on the page. Sometimes, the web server would simply not have the resources to
handle the request and timeout. The best solution for this issue was Ajax.

Getting JSON Data:


Q). What is JSON? What are the need of JSON? And explain about the JSON using AJAX?
JSON is another markup language to define data. JSON (JavaScript Object Notation) is much
easier to use with JavaScript than XML. When it comes to Ajax and JavaScript, JSON Web Services
are replacing XML Web Services.

JSON or JavaScript Object Notation is a lightweight text-based open standard designed for
human-readable data interchange. Conventions used by JSON are known to programmers, which
include C, C++, Java, Python, Perl, etc.
 JSON stands for JavaScript Object Notation.
 The format was specified by Douglas Crockford.
 It was designed for human-readable data interchange.
 It has been extended from the JavaScript scripting language.
 The filename extension is .json.
 JSON Internet Media type is application/json.
 The Uniform Type Identifier is public.json.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 60


Uses of JSON
 It is used while writing JavaScript based applications that includes browser extensions and
websites.
 JSON format is used for serializing and transmitting structured data over network
connection.
 It is primarily used to transmit data between a server and web applications.
 Web services and APIs use JSON format to provide public data.
 It can be used with modern programming languages.

Characteristics of JSON

 JSON is easy to read and write.


 It is a lightweight text-based interchange format.
 JSON is language independent.

There would be a situation when server would return JSON string against your request.
JQuery utility function getJSON() parses the returned JSON string and makes the resulting string
available to the callback function as first parameter to take further action.
Syntax : [selector].getJSON( URL, [data], [callback] );
the description of all the parameters:
URL: The URL of the server-side resource contacted via the GET method.
Data: An object whose properties serve as the name/value pairs used to construct a query string
to be appended to the URL, or a preformatted and encoded query string.
Callback: A function invoked when the request completes. The data value resulting from digesting
the response body as a JSON string is passed as the first parameter to this callback, and the status
as the second.
Many developers use JSON to pass AJAX updates between the client and the server.
Websites updating live sports scores can be considered as an example of AJAX. If these scores
have to be updated on the website, then they must be stored on the server so that the webpage
can retrieve the score when it is required. This is where we can make use of JSON formatted data.

Any data that is updated using AJAX can be stored using the JSON format on the web server. AJAX
is used so that javascript can retrieve these JSON files when necessary, parse them, and perform
one of the following operations :

 Store the parsed values in the variables for further processing before displaying them on
the webpage.

 It directly assigns the data to the DOM elements in the webpage, so that they are displayed
on the website.
The JSON Web Services on the web server in order to retrieve the details about the selected item.
The JSON web service would retrieve the data and convert into JSON and return a JSON string.
Instead of posting back to the server, the client would call the web service when an item was
selected from the list box.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 61


JSON – Syntax:
JSON syntax is basically considered as a subset of JavaScript syntax; it includes the following :

 Data is represented in name/value pairs.


 Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are
separated by , (comma).
 Square brackets hold arrays and values are separated by ,(comma).

Below is a simple example:

{
"book": [ {
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id": "07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
} ] }

Example:1
<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() {
$("#driver").click(function(event){
$.getJSON('/jquery/result.json', function(jd) {
$('#stage').html('<p> Name: ' + jd.name + '</p>');
$('#stage').append('<p>Age : ' + jd.age+ '</p>');
$('#stage').append('<p> Sex: ' + jd.sex+ '</p>');
}); }); });
</script> </head> <body>
<p>Click on the button to load result.html file:</p>
<div id="stage" style="background-color:blue;"> STAGE </div>
<input type="button" id="driver" value="Load Data" />
</body> </html>

JSON – DataTypes:
JSON format supports the following data types:

S. No. Type & Description

Number double- precision floating-point format in JavaScript

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 62


String double-quoted Unicode with backslash escaping

Boolean true or false

Array an ordered sequence of values

Value it can be a string, a number, true or false, null etc

Object an unordered collection of key:value pairs

Whitespace can be used between any pair of tokens

null empty

JSON – Objects:
Q) What are the JSON Objects and Explain?

 JSON objects are surrounded by curly braces {}.


 JSON objects are written in key/value pairs.
 Keys must be strings, and values must be a valid JSON data type (string, number, object,
array, boolean or null).
 Keys and values are separated by a colon.
 Each key/value pair is separated by a comma.

Accessing Object Values:

To access the object values by using dot (.) notation:

Example
myObj = { "name":"John", "age":30, "car":null };
x = myObj.name;
Looping an Object:

loop through object properties by using the for-in loop:

Example

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 63


myObj = { "name":"John", "age":30, "car":null };
for (x in myObj) {
    document.getElementById("demo").innerHTML += x;
}
Nested JSON Objects:

Values in a JSON object can be another JSON object.

Example: myObj = {


     "name":"John",
     "age":30,
     "cars": {
         "car1":"Ford",
         "car2":"BMW",
         "car3":"Fiat"
    }  }

Modify Values:

To use the dot notation to modify any value in a JSON object:

Example
myObj.cars.car2 = "Mercedes";
Delete Object Properties:

Use the delete keyword to delete properties from a JSON object:

Example
delete myObj.cars.car2;
Arrays as JSON Objects:
Example [ "Ford", "BMW", "Fiat" ]

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

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

1.Creating reading Objects:


JSON objects can be created with JavaScript. the various ways of creating JSON objects using
JavaScript:

1. Creation of an empty Object:

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 64


var JSONObj = {};

2. Creation of a new Object :


var JSONObj = new Object();
 Creation of an object with attribute bookname with value in string, attribute price with
numeric value. Attribute is accessed by using '.' Operator −

var JSONObj = { "bookname ":"VB BLACK BOOK", "price":500 };


Example: This is an example that shows creation of an object in javascript using JSON, save the
below code as json_object.htm

<html>
<head>
<title>Creating Object JSON with JavaScript</title>
<script language = "javascript" >
var JSONObj = { "name" : "tutorialspoint.com", "year" : 2005 };
document.write("<h1>JSON with JavaScript example</h1>");
document.write("<br>");
document.write("<h3>Website Name = "+JSONObj.name+"</h3>");
document.write("<h3>Year = "+JSONObj.year+"</h3>");
</script>
</head>
<body>
</body> </html>

To open Json Object using IE or any other javaScript enabled browser. It produces the result:

2. Creating Array Objects:


The following example shows creation of an array object in javascript using JSON, save the below
code as json_array_object.htm

<html>
<head>
<title>Creation of array object in javascript using JSON</title>
<script language = "javascript" >
document.writeln("<h2>JSON array object</h2>");
var books = { "Pascal" : [
{ "Name" : "Pascal Made Simple", "price" : 700 },
{ "Name" : "Guide to Pascal", "price" : 400 }],
"Scala" : [
{ "Name" : "Scala for the Impatient", "price" : 1000 },
{ "Name" : "Scala in Depth", "price" : 1300 }]
}
var i = 0
document.writeln("<table border = '2'><tr>");

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 65


for(i = 0;i<books.Pascal.length;i++){
document.writeln("<td>");
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td><b>Name</b></td><td width = 50>" + books.Pascal[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width = 50>" + books.Pascal[i].price +"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
for(i = 0;i<books.Scala.length;i++){
document.writeln("<td>");
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td><b>Name</b></td><td width = 50>" + books.Scala[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width = 50>" + books.Scala[i].price+"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
} document.writeln("</tr></table>");
</script>
</head> <body> </body> </html>

open Json Array Object using IE or any other javaScript enabled browser. It produces the result:

What is a Data Grid?


A datagrid is a table that displays the contents of a database or table along with sorting controls.
A datagrid is a table that displays the contents of a database or table along with sorting controls. In
we will providing this functionality, but also saving the user from waiting for the page to refresh
each time an operation is performed.

Step 1: Build a Data Grid Generator Class: We want to build a tool that will enable us to create
datagrids dynamically for any database table that we have. This means the code is not tied up to
any specific table structure, and, thus, is independent on the data itself. All the coder (the
developer who uses our class) must know is the name of the table to be transformed into a grid
and the primary key for that table. Here is the preface of the class that we will be developing for
the most part of this tutorial:

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 66


01 <?php
02 class Datagrid{
03     private $hide_pk_col = true;
04     private $hide_cols = array();
05     private $tbl_name = '';
06     private $pk_col = '';
07     private $headings = array();
08     private $tbl_fields = array();
09 }
10 ?>

UNIT – V
ANGULAR - JS
Introduction: A basic understanding of JavaScript and any text editor. As we are going to develop
web-based applications using AngularJS, it will be good if we can an understanding of other web
technologies such as HTML, CSS, AJAX, etc.
The designed to help to learn AngularJS as quickly and efficiently as possible. First, we will
learn the basics of AngularJS: directives, expressions, filters, modules, and controllers. Then it will
learn everything else you need to know about AngularJS: Events, DOM, Forms, Input, Validation,
Http, and more. It is licensed under the Apache license version 2.0.
The History of AJS is:
AngularJS is an open source web application framework. It was originally developed in
2009 by Misko Hevery and Adam Abrons. It is now maintained by Google. Its latest version is 1.4.3.
The idea turned out very well, and the project is now officially supported by Google.
Q). What is AngularJS? What are the features of AngularJS and explain?
AngularJS is a very powerful JavaScript Framework. It is used in Single Page Application
(SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive to
the user actions. [or]

AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.
AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.

AngularJS is a framework used to build large scale and high performance web application
while keeping them as easy-to-maintain.
AngularJS is open source, completely free, and used by thousands of developers around the
world. It is licensed under the Apache license version 2.0.
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 67
The Concept of Angular JS:

Features:
 AngularJS is a powerful JavaScript based development framework to create RICH Internet
Application(RIA).
 AngularJS provides developers options to write client side application (using JavaScript) in
a clean MVC(Model View Controller) way.
 Application written in AngularJS is cross-browser compliant. AngularJS automatically
handles JavaScript code suitable for each browser.
 AngularJS is open source, completely free, and used by thousands of developers around the
world. Its licensed under Apache License version 2.0.
Core Features:
The Following are most important core features of AngularJS:
 Data-binding: It is the automatic synchronization of data between model and view
components.
 Scope: The objects refers to the model. They act as a glue between controller and view.
 Controller: JavaScript functions that are bound to a particular scope.
 Services: AngularJS come with several built-in services for example $https: to make a
XMLHttpRequests.
 Filters: To select a subset of items from an array and returns a new array.
 Directives: Directives are markers on DOM elements (such as elements, attributes, css,
and more). These can be used to create custom HTML tags that serve as new, custom
widgets. AngularJS has built-in directives.
 Templates − These are the rendered view with information from the controller and
model. These can be a single file (like index.html) or multiple views in one page using
"partials".
 Routing: It is concept of switching views.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 68


 Model View Whatever: MVC is a design pattern for dividing an application into different
parts (called Model, View and Controller), each with distinct responsibilities.
 Deep Linking: Deep linking allows to encode the state of application in the URL so that it
can be bookmarked. The application can then be restored from the URL to the same state.
 Dependency Injection: AngularJS has a built-in dependency injection subsystem that
helps the developer by making the application easier to develop, understand, and test.
Advantages of AngularJS:
 AngularJS provides capability to create Single Page Application in a very clean and
maintainable way.
 AngularJS provides data binding capability to HTML thus giving user a rich and responsive
experience
 AngularJS code is unit testable.
 AngularJS uses dependency injection and make use of separation of concerns.
 AngularJS provides reusable components.
 With AngularJS, developer write less code and get more functionality.
 In AngularJS, views are pure html pages, and controllers written in JavaScript do the
business processing.
On top of everything, AngularJS applications can run on all major browsers and smart phones
including Android and iOS based phones/tablets.

Disadvantages of AngularJS:
The AngularJS comes with lots of plus points but same time we should consider the following
points:
 Not Secure − Being JavaScript only framework, application written in AngularJS are not
safe. Server side authentication and authorization is must to keep an application secure.
 Not degradable − If your application user disables JavaScript then user will just see the
basic page and nothing more.
The AngularJS Components:
The AngularJS framework can be divided into following three major parts −
 ng-app − This directive defines and links an AngularJS application to HTML.
 ng-model − This directive binds the values of AngularJS application data to HTML input
controls.
 ng-bind − This directive binds the AngularJS Application data to HTML tags.

Downloading AngularJS:
Q). Briefly Explain the Downloading Angular JS with example?

Downloading and hosting files locally:


There are two different options legacy and latest. The names itself are self
descriptive. legacy has version less than 1.2.x and latest has 1.5.x version.
We can also go with the minified, uncompressed or zipped version.
Download AngularJS 1 : click on this button, a screen as below would be seen

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 69


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

CDN access : Access to a CDN. The CDN will give a access around the world to regional data
centers, i.e Google host. This means using CDN moves the responsibility of hosting files from the
own servers to a series of external ones. The advantage AJS if the visitor to webpage has already
downloaded a copy of AngularJS from the same CDN, it won't have to be re-downloaded.

Try the new angularJS 2: Click on this button to download Angular JS beta 2 version.This version
is very fast, mobile supported and flexible compare to legacy and latest of AngularJS 1.We are
using the CDN versions.

Example: To write a simple example using AngularJS library. Let us create an HTML
file myfirstexample.html as below:

<!doctype html>
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.2/angular.min.js"></script>
</head>
<body ng-app = "myapp">
<div ng-controller = "HelloController" >
<h2>Welcome {{helloTo.title}} to the world of Tutorialspoint!</h2>
</div>
<script>
angular.module("myapp", [])
.controller("HelloController", function($scope) {
$scope.helloTo = {};
$scope.helloTo.title = "AngularJS";
});
</script>
</body>
</html>

Following sections describe the above code in detail −

Include AngularJS:

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 70


We have included the AngularJS JavaScript file in the HTML page so we can use AngularJS

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

If you want to update into latest version of Angular JS, use the following script source or else
Check the latest version of AngularJS on their official website.

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

AngularJS - Built – in Directives:


Q). Explain about the AngularJS Built in Directives with example?

AngularJS directives are used to extend HTML. These are special attributes starting with ng-
prefix. The following directives are :
1. ng-app : This directive starts an AngularJS Application.
2. ng-init : This directive initializes application data.
3. ng-model : It binds the values of AngularJS application data to HTML input controls.
4. ng-repeat : This directive repeats html elements for each item in a collection.

1. ng-app directive:
ng-app directive starts an AngularJS Application. It defines the root element. It
automatically initializes or bootstraps the application when web page containing AngularJS
Application is loaded.

It is also used to load various AngularJS modules in AngularJS Application. In following


example: <div ng-app = "">

... </div>

2. ng-init directive:
ng-init directive initializes an AngularJS Application data. It is used to put values to the
variables to be used in the application. To initialize an array of countries. We're using JSON
syntax to define array of countries.

Example:

<div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'}, {locale:'en-GB',name:'United


Kingdom'}, {locale:'en-FR',name:'France'}]">
...
</div>

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 71


3. ng-model directive:
This directive binds the values of AngularJS application data to HTML input controls. To
defined a model named "name".

<div ng-app = "">


...
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
</div>

4. ng-repeat directive:
ng-repeat directive repeats html elements for each item in a collection. To iterated over
array of countries.

Example:

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

Result:

Sample Application

Enter your Name: 

Hello !

List of Countries with locale:

1. Country: United States, Locale: en-US


2. Country: United Kingdom, Locale: en-GB
3. Country: France, Locale: en-FR

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 72


AngularJS - Expressions:
Q). Explain about AngularJS – Expressions with example?

Expressions are used to bind application data to html. Expressions are written inside
double braces like {{ expression}}. Expressions behaves in same way as ng-bind directives.
AngularJS application expressions are pure javascript expressions and outputs the data where
they are used. AngularJS expressions are much like JavaScript expressions: It contain literals,
operators, variables and etc.
Ex: {{ 5 + 5 }} or {{ firstName + " " + lastName }}

Numbers: <p>Expense on Books : {{cost * quantity}} Rs</p>


Strings: <p>Hello {{student.firstname + " " + student.lastname}}!</p>
Object: <p>Roll No: {{student.rollno}}</p>
Array: <p>Marks(Math): {{marks[3]}}</p>

Example: <!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>

AngularJS Expressions vs. JavaScript Expressions:

 JavaScript expressions, AngularJS expressions can contain literals, operators, and variables.
 JavaScript expressions, AngularJS expressions can be written inside HTML.
 AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript
expressions do.
 AngularJS expressions support filters, while JavaScript expressions do not.

AngularJS- Modules:

Q). Explain about the AngularJS – Modules with example?


AngularJS supports modular approach. Modules are used to separate logics, like 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 modules :

1. Application Module: used to initialize an application with controller(s).


2. Controller Module : used to define the controller.

1. Application Module:

To declared an application mainApp module using angular.module function. It passed an


empty array to it. This array generally contains dependent modules.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 73


mainApp.js

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

2. Controller Module:
To declared a controller studentController module using mainApp.controller function.

used application module using ng-app directive and controller using ng-controller
directive. Its imported mainApp.js and studentController.js in the main html page.
Example: Following example will showcase all the above mentioned modules.1. testAngularJS.htm

<html> <head>

<title>Angular JS Modules</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src = "/angularjs/src/module/mainApp.js"></script>
<script src = "/angularjs/src/module/studentController.js"></script>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style> </head> <body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "studentController">
<table border = "0">
<tr>
<td>Enter first name:</td>
<td><input type = "text" ng-model = "student.firstName"></td>
</tr>
<tr>
<td>Enter last name: </td>
<td><input type = "text" ng-model = "student.lastName"></td>
</tr>
<tr>
<td>Name: </td>
<td>{{student.fullName()}}</td>
</tr>
<tr>
<td>Subject:</td>
<td>
<table> <tr>
<th>Name</th>
<th>Marks</th>
</tr>
<tr ng-repeat = "subject in student.subjects">
<td>{{ subject.name }}</td>
<td>{{ subject.marks }}</td>
</tr>
</table> </td> </tr> </table> </div>
</body> </html>

2.mainApp.js

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

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 74


3.studentController.js

mainApp.controller("studentController", function($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fees:500,
subjects:[
{name:'Physics',marks:70},
{name:'Chemistry',marks:80},
{name:'Math',marks:65},
{name:'English',marks:75},
{name:'Hindi',marks:67} ],
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
} }; });

Result:

AngularJS Sample Application


Enter first name:

Enter last name:

Name: Mahesh Parashar

Name Marks
Physics 70
Chemistry 80
Subject:
Math 65
English 75
Hindi 67

AngularJS – Controllers:
Q). Explain about Angular Controller with example?
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

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 75


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>

 studentController defined as a JavaScript object with $scope as argument.


 $scope refers to application which is to use the studentController object.
 $scope.student is property of studentController object.
 firstName and lastName are two properties of $scope.student object. We've passed the
default values to them.
 fullName is the function of $scope.student object whose task is to return the combined
name.
 In fullName function we're getting the student object and then return the combined name.
 As a note, we can also define the controller object in separate JS file and refer that file in
the html page.

 <script>
 function studentController($scope) {
 $scope.student = {
 firstName: "Mahesh",
 lastName: "Parashar",
 fullName: function() {
 var studentObject;
 studentObject = $scope.student;
 return studentObject.firstName + " " + studentObject.lastName;
 } }; } </script>

Enter first name: <input type = "text" ng-model = "student.firstName"><br>


Enter last name: <input type = "text" ng-model = "student.lastName"><br>
<br>
You are entering: {{student.fullName()}}

Angular – Scope:
Q). Explain about the Angular Scope with example?

Scope is a special javascript object which plays the role of joining controller with the views. Scope
contains the model data. In controllers, model data is accessed via $scope object. If we consider an
AngularJS application to consist of:

 View, which is the HTML.


 Model, which is the data available for the current view.
 Controller, which is the JavaScript function that makes/changes/removes/controls the
data.

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 76


Root Scope : All applications have a $rootScope which is the scope created on the HTML element
that contains the ng-appdirective. The rootScope is available in the entire application.

<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller("shapeController", function($scope) {
$scope.message = "In shape controller";
$scope.type = "Shape";
});
</script>

Following are the important points to be considered in above example.


 $scope is passed as first argument to controller during its constructor definition.
 $scope.message and $scope.type are the models which are to be used in the HTML page.
 We've set values to models which will be reflected in the application module whose
controller is shapeController.
 We can define functions as well in $scope.

Scope Inheritance:
Scope are controllers specific. If we defines nested controllers then child controller will inherit
the scope of its parent controller.

<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller("shapeController", function($scope) {
$scope.message = "In shape controller";
$scope.type = "Shape";
});
mainApp.controller("circleController", function($scope) {
$scope.message = "In circle controller";
});
</script>

 To set values to the models in shapeController.


 The overridden message in child controller circleController. When "message" is used
within module of controller circleController, the overridden message will be used.
Angular – Dependency Injuction:
Q). Explain about Angular Dependency Injuction with example?
Dependency Injection is a software design pattern in which components are given their
dependencies instead of hard coding them within the component. The relieves a component from
locating the dependency and makes dependencies configurable. This helps in making
components reusable, maintainable and testable.

AngularJS provides a supreme Dependency Injection mechanism. It provides following core


components which can be injected into each other as dependencies.

 value
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 77
 factory
 service
 provider
 constant
value : value is simple javascript object and it is used to pass values to controller during config
phase.
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.
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.
Provider: provider is used by AngularJS internally to create services, factory etc. during config
phase(phase during which AngularJS bootstraps itself). Provider is a special factory method with
a method get() which is used to return the value/service/factory.
Constant : constants are used to pass values at config phase considering the fact that value can not
be used to be passed during config phase.
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>
</div> <script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
} return factory;
}; }); });
mainApp.value("defaultInput", 5);
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
} return factory;
});
mainApp.service('CalcService', function(MathService){
this.square = function(a) {
return MathService.multiply(a,a);

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 78


} });
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
} });
</script> </body> </html>

Result: Open textAngularJS.htm in a web browser.


AngularJS Sample Application

Enter a number:5   X2

Result: 25

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 79


Filters:
Q). Explain about the Angular filters with example?

Angular filters are a way of processing data and returning a specific set of logic. It can be
absolutely anything, from processing a date stamp into a formatted time, to a list of names that
begin with a specific letter.
Filters are used to change modify the data and can be clubbed in expression or directives
using pipe character. Following is the list of commonly used filters.

Sr.No. Name Description

1 uppercase converts a text to upper case text.

2 lowercase converts a text to lower case text.

3 currency formats text in a currency format.

4 filter filter the array to a subset of it based on provided criteria.

5 orderby orders the array based on provided criteria.

Filters can be used in two different ways, 1. the DOM via a pipe | character inside our
expressions, which Angular parses. 2. The second way is using the $filter Service, which we can
dependency inject and use within our JavaScript instead of HTML.
The Angular's built-in filters are:
 Single value Filters
 Data set Filters 
 Date filters
 JSON filter
 limitTo and orderBy
 Controller ($scope) Filters
Example:
function SomeCtrl () {
this.namesStartingWithA = function () {
}; }

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 80


angular
.module('app')
.controller('SomeCtrl', SomeCtrl);

AngularJS Events:
To add AngularJS event listeners to your HTML elements by using one or more of these
directives:

 ng-blur
 ng-change
 ng-click
 ng-copy
 ng-cut
 ng-dblclick
 ng-focus
 ng-keydown
 ng-keypress
 ng-keyup
 ng-mousedown
 ng-mouseenter
 ng-mouseleave
 ng-mousemove
 ng-mouseover
 ng-mouseup
 ng-paste

The event directives allows us to run AngularJS functions at certain user events. An AngularJS
event will not overwrite an HTML event, both events will be executed.

Mouse Events: Mouse events occur when the cursor moves over an element, in this order:

1. ng-mouseenter
2. ng-mouseover
3. ng-mousemove
4. ng-mouseleave

Or when a mouse button is clicked on an element, in this order:

1. ng-mousedown
2. ng-mouseup
3. ng-click

To add mouse events on any HTML element.

Example: Increase the count variable when the mouse moves over the H1 element:
<div ng-app="myApp" ng-controller="myCtrl">
<h1 ng-mousemove="count = count + 1">Mouse over me!</h1>

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 81


<h2>{{ count }}</h2>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.count = 0;
});
</script>

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 82


JS- AJAX

JS with JSON Arrays:


Introduction : JSON is derived from the JavaScript programming language, it is a natural choice
to use as a data format in JavaScript. JSON, short for JavaScript Object Notation, is usually
pronounced like the name “Jason.”
To begin thinking about where you may use JSON in your JavaScript programs, some general use
cases of JSON include:

 Storing data
 Generating data structures from user input
 Transferring data from server to client, client to server, and server to server
 Configuring and verifying data

To provide with an introduction to working with JSON in JavaScript. To make the most use of this
introduction, it should have some familiarity with the JavaScript programming language.

JSON Format
JSON’s format is derived from JavaScript object syntax, but it is entirely text-based. It is a key-
value data format that is typically rendered in curly braces.

Working with Arrays:


Arrays are very versatile for storing data, and can be searched, tested, and have functions applied
to them in V8 using the following ECMAScript 5 functions:

1. Searching the content of an Array:

Array.isArray(array) Returns true if a variable is an array, false if it is not.


indexOf(searchElement[, Returns the first (least) index of an element within the
fromIndex]) array equal to the specified value, or -1 if none is found.
The search can optionally begin at fromIndex.
lastIndexOf(searchElement[, Returns the last (greatest) index of an element within the
fromIndex]) array equal to the specified value, or -1 if none is
found.The array is searched backwards, starting at
fromIndex.
The indexOf() and lastIndexOf() functions are very useful for searching an array for a particular value,
if necessary.
For example, to check whether a particular value is present in an array:

function process(argv) {

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 83


if(argv.indexOf('help')) {
console.log('This is the help text.');
}
}
process(['foo', 'bar', 'help']);

2. Applying function to every item in an Array:

filter(callback[, Creates a new array with all of the elements of this array for which the provided
thisObject]) filtering function returns true. If a thisObject parameter is provided to filter, it will
be used as the this for each invocation of the callback. IE9
forEach(callback[ Calls a function for each element in the array.
, thisObject])
map(callback[, Creates a new array with the results of calling a provided function on every
thisObject]) element in this array.

filter(), map() and forEach() all call a callback with every value of the array. This can be useful for
performing various operations on the array. 

3. Array functions: The Array functions are:


sort([compareFunction]) Sorts the elements of an array.
concat(value1, value2, ..., valueN) Returns a new array comprised of this array joined with
other array(s) and/or value(s).
join(separator) Joins all elements of an array into a string.
slice(begin[, end] Extracts a section of an array and returns a new array.
splice(index [,howMany][,element1[, ... Adds and/or removes elements from an array.
[, elementN]]]
reverse Reverses the order of the elements of an array -- the first
becomes the last, and the last becomes the first.

Example:var a = [ 'a', 'b', 'c' ];

var b = [ 1, 2, 3 ];
console.log( a.concat(['d', 'e', 'f'], b) );
console.log( a.join('! ') );
console.log( a.slice(1, 3) );
console.log( a.reverse() );
console.log( ' --- ');
var c = a.splice(0, 2);
console.log( a, c );
var d = b.splice(1, 1, 'foo', 'bar');
console.log( b, d );

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 84


JQuery Lab Programs

1. To select all elements with tag selector


1. Write a Java script Program, which makes use of Tag Selector and it selects all the
elements with a tag name p.
<html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var pars = $("p");
for( i=0; i<pars.length; i++ ){
alert("Found paragraph: " + pars[i].innerHTML);
}
});
</script>
</head>
<body>
<div>
<p class="myclass">This is a paragraph.</p>
<p id="myid">This is second paragraph.</p>
<p>This is third paragraph.</p>
</div>
</body>
</html>
RESULT:

2. DOM Elements – Back ground Color


2. Write a JQuery program to implement DOM CONCEPT, i. e select second division and will
apply yellow color to its background.

<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
/* This would select second division only*/
$("#div2").css("background-color", "yellow");
});

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 85


</script>
</head>
<body>
<div class="big" id="div1">
<p>This is first division of the DOM.</p>
</div>
<div class="medium" id="div2">
<p>This is second division of the DOM.</p>
</div>
<div class="small" id="div3">
<p>This is third division of the DOM</p>
</div>
</body>
</html>

RESULT:
This will produce the following result:
This is first division of the DOM.
This is second division of the DOM.
This is third division of the DOM

3. UpLoad an Image with Source selector


3. Write a JQuery Program to 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>

Result:

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 86


4. To Create an Input Boxs
4. Write a JQuery Program to set the HTML content of the first input box in the second
paragraph?
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript" src="/jquery/jquery-1.3.2.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var content = $("input").val();
$("p#pid2").text(content);
});
</script>
<style>
.red { color:red; }
.green { color:green; }
</style>
</head>
<body>
<input type="text" value="First Input Box"/>
<input type="text" value="Second Input Box"/>
<p class="green" id="pid1">This is <i>first paragraph</i>.</p>
<p class="red" id="pid2">This is second paragraph.</p>
</body>
</html>
Result:

5. To implements DOM Traversing Methods


5. Write a JQuery Programm To implement DOM Traversing methods? i.e which selects all
the <span> elements available inside different <p> elements?

<html>
<head>
<title>the title</title>

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 87


<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("p").find("span").addClass("selected");
});
</script>
<style>
.selected { color:red; }
</style> </head>
<body>
<p>This is 1st paragraph and <span>THIS IS RED</span></p>
<p>This is 2nd paragraph and <span>THIS IS ALSO RED</span></p>
</body> </html>

Result:

This is 1st paragraph and THIS IS RED

This is 2nd paragraph and THIS IS ALSO RED

5. To implements MAP Method


6. Write a JQuery Program to perform MAP(Calling) method?

<html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
var mappedItems = $("li").map(function (index) {
var replacement = $("<li>").text($(this).text()).get(0);
if (index == 0) {
// make the first item all caps
$(replacement).text($(replacement).text().toUpperCase());
} else if (index == 1 || index == 3) {
// delete the second and fourth items
replacement = null;
} else if (index == 2) {
// make two of the third item and add some text
replacement = [replacement,$("<li>").get(0)];
$(replacement[0]).append("<b> - A</b>");
$(replacement[1]).append("Extra <b> - B</b>");
}
// replacement will be an dom element, null,
// or an array of dom elements
return replacement;
});
$("#results").append(mappedItems);
});
</script>
<style>
body { font-size:16px; }
ul { float:left; margin:0 30px; color:blue; }

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 88


#results { color:red; }
</style>
</head>
<body>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
</ul>
<ul id="results">
</ul> </body> </html>

Result:

CSS Selector methods:


7. CSS Selectors – Height & Width
7. Write a JQuery program to implement CSS Selectors using Width & Height methods?
<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() {
$("div:first").width(100);
$("div:first").css("background-color", "blue");
});
</script>
<style>
div{ width:70px; height:50px; float:left; margin:5px;
background:red; cursor:pointer; }
</style>
</head>
<body>
<div></div>
<div>d</div>
<div>d</div>
<div>d</div>
<div>d</div>
</body>
</html>
Result:

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 89


Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 90
8. CSS Properties – Validation
8. Write a JQuery program to implement CSS (properties) methods sets a key/value object
as style properties to all matched 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() {
$("div").click(function () {
var color = $(this).css("background-color");
$("#result").html("That div is <span>" + color + "</span>.");
$("#result").css({'color': color,
'font-weight' : 'bold',
'background-color': 'gray'});
});
});
</script>
<style>
div { width:60px; height:60px; margin:5px; float:left; }
</style>
</head>
<body>
<p>Click on any square:</p>
<span id="result"> </span>
<div style="background-color:blue;"></div>
<div style="background-color:rgb(15,99,30);"></div>
<div style="background-color:#123456;"></div>
<div style="background-color:#f11;"></div>
</body>
</html>
Result:

Click on any square:

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 91


9. CSS – InnerWidth()Method
9. Write a JQuery program to implement CSS (properties) i.e innerWidth( ) Method for the
first matched element?
<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() {
$("div").click(function () {
var color = $(this).css("background-color");
var width = $(this).innerWidth();
$("#result").html("Inner Width is <span>" +
width + "</span>.");
$("#result").css({'color': color,
'background-color':'gray'});
}); });
</script> <style>
#div1{ margin:10px;padding:12px;
border:2px solid #666;
width:60px;}
#div2 { margin:15px;padding:5px;
border:5px solid #666;
width:60px;}
#div3 { margin:20px;padding:4px;
border:4px solid #666;
width:60px;}
#div4 { margin:5px;padding:3px;
border:3px solid #666;
width:60px;} </style> </head>
<body>
<p>Click on any square:</p>
<span id="result"> </span>
<div id="div1" style="background-color:blue;"></div>
<div id="div2" style="background-color:pink;"></div>
<div id="div3" style="background-color:#123456;"></div>
<div id="div4" style="background-color:#f11;"></div>
</body>
</html>
Result:

Click on any square:


Click on any square:

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 92


10. CSS – ScrollLeft() Method
10. Write a JQuery program to implement CSS scrollLeft( ) Method gets the scroll left of the
first matched element and its method works for both visible and hidden 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(){
$("div.demo").scrollLeft( 200 );
$("div.demo").mousemove(function () {
var left = $("div.demo").scrollLeft();
$("#result").html("left offset: <span>" +
left + "</span>.");
});
});
</script>
<style>
div.demo {
background:#CCCCCC none repeat scroll 0 0;
border:3px solid #666666;
margin:5px;
padding:5px;
position:relative;
width:200px;
height:100px;
overflow:auto;
}
div.result{
margin:10px;
width:100px;
height:100px;
margin:5px;
float:left;
background-color:blue;
}
p { margin:10px;
padding:5px;
border:2px solid #666;
width:1000px;
height:1000px;
}
</style>
</head>
<body>
<div class="demo"><p>Hello</p></div>
<span>Scroll horizontal button to see the result:</span>
<div class="result"><span id="result"></span></div>
</body>
</html>

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 93


Result:

DOM Manipulation:
11. DOM Elements – WrapAll() Method
11. Write a JQuery program to perform an Inserting DOM Elements using wrapAll( html )
Method?
<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() {
$("div").click(function () {
var content = "<div class='div'></div>";
$("div").wrapAll( content );
});
});
</script>
<style>
.div{ margin:10px;padding:12px;
border:2px solid #666;
width:60px;
}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<div class="div" id="destination">THIS IS TEST</div>
<div class="div" style="background-color:blue;">ONE</div>
<div class="div" style="background-color:green;">TWO</div>
<div class="div" style="background-color:red;">THREE</div>
</body>
</html>

Result:

Click on any square below to see the result:

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 94


12. Event Handler Methods
12. Write a JQuery program to implement Event Handlers Using the jQuery Event Model?
<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() {
$("div").click(function(event){
alert("This is : " + $(this).text());
// Comment the following to see the difference
event.stopPropagation();
});
});
</script>
<style>
div{ margin:10px;padding:12px;
border:2px solid #666;
width:160px;
}
</style>
</head>
<body>
<p>Click on any box to see the effect:</p>
<div id="div1" style="background-color:blue;">
OUTER BOX
<div id="div2" style="background-color:red;">
INNER BOX
</div>
</div>
</body>
</html>
Result:

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 95


Click on any square below to see the result:

13. Write a JQuery program to implement Event Manipulation Methods i.e off( events [,
selector ] [, handler(eventObject) ] ) and on() method?
<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
function aClick() {
$("div").show().fadeOut("slow");
}
$("#bind").click(function () {
$("#theone").on("click", aClick).text("Can Click!");
});
$("#unbind").click(function () {
$("#theone").off("click", aClick).text("Does nothing...");
});
});
</script>
<style>
button { margin:5px; }
button#theone { color:red; background:yellow; }
</style>
</head>
<body>
<button id="theone">Does nothing...</button>
<button id="bind">Bind Click</button>
<button id="unbind">Unbind Click</button>
<div style="display:none;">Click!</div>
</body>
</html>

Result:
Click on any square below to see the result:

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 96


AJAX:
14.Write a JQuery program to Load Simple Data (static or dynamic data) using JQuery
AJAX?
<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() {
$("#driver").click(function(event){
$('#stage').load('/jquery/result.html');
});
});
</script>
</head>
<body>
<p>Click on the button to load result.html file:</p>
<div id="stage" style="background-color:blue;">
STAGE
</div>
<input type="button" id="driver" value="Load Data" />
</body>
</html>

Result:

Click on the button to load result.html file

15.Write a JQuery program to perform the Passing Data to the Server using AJAX?

<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() {
$("#driver").click(function(event){
var name = $("#name").val();
$("#stage").load('/jquery/result.php', {"name":name} );
});
});
</script>
</head>
<body>
<p>Enter your name and click on the button:</p>
<input type="input" id="name" size="40" /><br />
<div id="stage" style="background-color:blue;">

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 97


STAGE
</div>
<input type="button" id="driver" value="Show Result" />
</body>
</html>

Here is the code written in result.php script:

<?php
if( $_REQUEST["name"] )
{
$name = $_REQUEST['name'];
echo "Welcome ". $name;
}
?>

Enter your name and click on the button:

16. Write a JQuery program to implement GET DATA using serializeArray( ) Method in
AJAX ?

<?php
if( $_REQUEST["name"] )
{
$name = $_REQUEST['name'];
echo "Welcome ". $name;
$age = $_REQUEST['age'];
echo "<br />Your age : ". $age;
$sex = $_REQUEST['sex'];
echo "<br />Your gender : ". $sex;
}
?>

Following is a simple example showing the usage of this method:

<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$.post(
"serialize.php",
$("#testform").serializeArray(),
function(data) {
$('#stage1').html(data);
}
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 98
);
var fields = $("#testform").serializeArray();
$("#stage2").empty();
jQuery.each(fields, function(i, field){
$("#stage2").append(field.value + " ");
});
});
});
</script>
</head>
<body>
<p>Click on the button to load result.html file:</p>
<div id="stage1" style="background-color:blue;">
STAGE - 1
</div>
<br />
<div id="stage2" style="background-color:blue;">
STAGE - 2
</div>
<form id="testform">
<table>
<tr>
<td><p>Name:</p></td>
<td><input type="text" name="name" size="40" /></td>
</tr>
<tr>
<td><p>Age:</p></td>
<td><input type="text" name="age" size="40" /></td>
</tr>
<tr>
<td><p>Sex:</p></td>
<td> <select name="sex">
<option value="Male" selected>Male</option>
<option value="Female" selected>Female</option>
</select></td>
</tr>
<tr>
<td colspan="2">
<input type="button" id="driver" value="Load Data" />
</td> </tr> </table> </form> </body>
</html>

Result:

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 99


Click on the button to load result.html file:

EFFECTS:

17. Write a JQuery program to perform the JQuery Effects using Showing and Hiding
Elements?
<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#show").click(function () {
$(".mydiv").show( 1000 );
});
$("#hide").click(function () {
$(".mydiv").hide( 1000 );
}); });
</script>
<style>
.mydiv{ margin:10px;padding:12px; border:2px solid #666; width:100px;
height:100px;}
</style> </head>
<body>
<div class="mydiv">
This is a SQUARE
</div>
<input id="hide" type="button" value="Hide" />
<input id="show" type="button" value="Show" />
</body> </html>
Result:

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 100


18. Write a JQuery program to perform the Effects JQuery Effect Slide up and slide down?
<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#show").click(function () {
jQuery
286
$(".mydiv").show( 100 );
});
$("#hide").click(function () {
$(".mydiv").hide( 100 );
});
});
</script>
<style>
.mydiv{ margin:10px;padding:12px; border:2px solid #666; width:100px;
height:100px;}
</style>
</head>
<body>
<div class="mydiv">
This is a SQUARE.
</div>
<input id="hide" type="button" value="Hide" />
<input id="show" type="button" value="Show" />
</body>
</html>

Result:

Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 101

You might also like