Advanced Java Script
Advanced Java Script
List of Questions
Essay Questions:
1. Discuss about jQuery.
2. Explain the following in JQuery.
(a) Functions (b) Arguments (c) Scope (d) Built – in function (d) Callback functions
3. Explain in detail about jQuery selectors with examples.
4. Explain jQuery DOM attributes with example each.
5. List out methods to manipulate JQuery DOM attributes and describe them with suitable
examples.
6. Briefly explain about JQuery – DOM Traversing.
7. List out JQuery DOM Traversing Methods and describe them.
Essay Questions:
1. How to apply and return CSS properties using jQuery CSS Methods. Explain with an example.
2. List out jQuery dimension methods and display all the dimensions using related methods.
3. How to set and return element width in jQuery. Explain with an example.
4. How to set and return element height in JQuery. Explain with an example.
5. Explain in detail about DOM Content manipulation in JQuery with an example.
6. Explain in detail about DOM Element Replacement in JQuery with an example.
7. Explain how to remove DOM Element in JQuery with an example.
8. Explain how to insert DOM Element in JQuery with an example.
9. List out various types of DOM event in JQuery and describe them.
10. How to establish event handlers on DOM elements in JQuery. Explain with an example.
11. How to remove event handlers that are established on DOM elements in JQuery. Explain with an
example.
12. Explain how to hide and show the elements in JQuery with an example.
13. Explain how to apply slide effect for the elements in JQuery with an example.
14. Explain how to apply fade effect for the elements in JQuery with an example.
15. Explain how to apply custom animations for the elements in JQuery with an example.
1
Advanced Java Script
Essay Questions:
1. How to download JQuery UI.
2. Give the syntax of JQuery UI Interaction methods.
3. Give the syntax of JQuery UI Widget methods.
4. Explain about consuming JQuery plugins from third party websites with an example.
5. Explain about JQuery validation plug – in.
Essay Questions:
1. Explain how to insert, delete and update data into database using JQuery-Ajax.
2. Explain about grid development using JQuery-Ajax.
3. Explain about JSON objects.
2
Advanced Java Script
Essay Questions:
1. How to download AngularJS.
2. Explain about AngularJS Expressions?
3. Explain about AngularJS Modules?
4. Explain about AngularJS Controllers?
5. Explain about AngularJS Scope?
6. Explain about AngularJS Dependency Injection?
7. Explain about AngularJS Filters?
8. Explain about AngularJS Events?
9. Explain about AngularJS Ajax?
10. Explain about AngularJS Routing?
11. Explain about AngularJS Validation?
12. Explain about AngularJS $q?
13. Explain how to create AngularJS registration form?
14. Explain how to create AngularJS login form?
15. Explain about AngularJS CRUD Operations?
Programs
1. Using JQuery find all textareas and makes a border. Then adds all paragraphs to the JQuery
object to set their borders red.
2. Using JQuery add the class “w3r_font_color”and w3r_background to the last paragraph element.
3. Using JQuery add a new class to an element that already has a class.
4. Using JQuery insert some HTML after all paragraphs.
5. Using JQuery insert a DOM element after all paragraphs.
6. Convert three headers and content panels into an accordion. Initialize the accordion and specify
the animate option.
7. Convert three headers and content panels into an accordion. Initialize the accordion and specify
the height.
8. Create a pre-populated list of values and delay in milliseconds between a keystroke occurs and
a search is performed.
9. Initialize the button and specify the disable option.
3
Advanced Java Script
4
Advanced Java Script
Unit – I
JQuery – Basics
Essay Questions
Q1. Discuss about JQuery.
JQuery is fast, lightweight and feature – rich client side Java Script Library / Framework which
helps in to traverse HTML DOM, make animations, add Ajax interaction, manipulate the page
content, change the style and provide cool UI effect.
Advantages of JQuery:
a) Easy to use and learn.
b) Easily expandable.
c) Cross-browser support (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+)
d) Easy to use for DOM manipulation and traversal.
e) Large pool of built in methods.
f) AJAX Capabilities.
g) Methods for changing or applying CSS, creating animations.
h) Event detection and handling.
2) Deployment.
The production version is quite useful at development time as JQuery is open source and it is
possible to make changes in production version.
But the deployment version is minified version or compressed version so it is impossible to
make changes in it. Because it is compressed, its size is very less than the production version and so
it loads quickly and saves bandwidth.
Both versions can be downloaded from JQuery.com. There are two ways to download JQuery.
1. The JQuery library is a single Java Script file and it can be referenced with the HTML
<script> tag (<script> tag should be inside the <head> section):
<head>
<script src=”jquery-3.3.1.min.js”></script>
</head>
2. The second way is to include it from a CDN.
Content delivery network or content distribution network (CDN) is a large distributed
system of servers deployed in multiple data centers across the Internet. The goal of a CDN is
to serve content to end-users with high availability and high performance.
5
Advanced Java Script
6
Advanced Java Script
7
Advanced Java Script
a) Functions:
A function in java script can be either named or anonymous.
A named function can be defined using function keyword as follows:
Function named() {//do some stuff here}
An anonymous function can be defined in similar way as a normal function but it would not
have any name. An anonymous function can be assigned to a variable or passed to a method as
shown below:
var handler=function(){
//do some stuff here
}
JQuery makes use to anonymous functions very frequently as follows:
$(documents).ready(function(){
//do some stuff here
});
b) Arguments:
JavaScript variable argument is a kind of array which has length property.
Example:
Function func(x){
Console. (typeof x, arguments.length);
}
func( ); //”undefinded”,0
func(1); //”number”,1
func(“1”, “2”, “3”); //”string”, 3
The arguments object also has a callee property, which refers to the inside of the function. For
example:
Function func( ){
Return arguments.callee;
}
func( ); //func
c) Scope:
The scope of a variable is the region of your program in which it is defined. Java Script variable will
have only two scopes.
Global Scope: A global variable has global scope which means it is defined everywhere in java
script code.
Local Scope: A local variable will be visible only within a function where it is defined. Function
parameters are always local to that function. Within body of function, a local variable takes
precedence over a global variable with the same name:
8
Advanced Java Script
d) Built in functions:
JavaScript built-in functions can be used to manipulate string numbers and dates.
Method Description
charAt( ) Returns the character at the specified index.
concat( ) Combines the text of two strings and returns a new string.
forEach( ) Calls a function for each element in the array.
IndexOf( ) Returns the index within the calling string object of the first occurrence of the
specified value, or – 1 if not found.
length( ) Returns the length of the string.
pop( ) Removes the last element from an array and returns that element.
push( ) Adds one or more elements to the end of an array and returns the new length of
the array
reverse( ) Reverses the order of the elements of an array, the first becomes the last, and the
last becomes the first.
sort ( ) Sorts the elements of an array
substr ( ) Returns the characters in a string beginning at the specified location through the
specified number of characters.
toLowerCase( ) Returns the calling string value converted to lower case.
tostring( ) Returns the string representation of the number’s value.
toUpperCase( ) Returns the calling string value converted to uppercase.
e) Callback Functions:
JavaScript statements are executed line by line. But, since JQuery effect takes some time to
finish the next line code may execute while the previous effect is still running. To prevent this from
happening JQuery provides a callback function for each effect method.
A callback function is a function that is executed once the effect is complete. The callback
function is passed as an argument to the effect methods and they typically appear as the last
argument of the method. For example, the basic syntax of the JQuery slideToggle( ) effect method
with a callback function can be given with
$(selector).slideToggle(duration, callback);
9
Advanced Java Script
Consider the following example in which the slideToggle( ) and alert( ) statements are
placed next to each other. Here, the alert will be displayed immediately once you click the trigger
button without waiting for slide toggle effect to complete.
<script type=”text/javascript”>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“p”).slideToggle(“slow”);
alert(“The slide toggle effect has completed.”);
});
});
</script>
And, here’s the modified version of the previous example in which the alert( ) statement is placed
inside a callback function for the slideToggle( ) method. Now, the alert message will be displayed
once the slide toggle effect has completed.
<script>
$(document).ready(function( ){
$(“.btn1”).click(function( ){
$(“p”).slideToggle(1000, function( ){
alert(“Hide( ) method is finished!”);
});
});
});
</script>
10
Advanced Java Script
Example:
$(“p”) selects all the elements with tag name <p> in the document.
<html>
<head>
<title> The JQuery Example</title>
<script type=“text/javascript”
src=”https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”>
</script>
<script type=”text/javascript” language=”javascript”>
$(documents).ready(function( )
{
$(“p”).css(“background-color”, “yellow”);
});
</script>
</head>
<body>
<div>
<p> This is a paragraph.</p>
<div>
</body>
</html>
Output:
This is a paragraph.
Example:
$(“#test”) selects all elements having (id=test> in the document.
<!DOCTYPE html>
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script>
<script>
11
Advanced Java Script
$(document).ready(function( ) {
$(“button”).click(function( ){
$(“#test”).hide( );
});
});
</script>
</head>
<body>
<h2> This is a heading</h2>
<p> This is a paragraph.</p>
<p id=“test”> This is another paragraph.</p>
<button> Click me</button>
</body>
</html>
Output: When a user clicks on a button, the element with id=“test” will be hidden
This is a heading This is a heading
This is another paragraph. This is a paragraph
Click me Click me
<!DOCTYPE html>
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script>
<script>
$(document).ready(function( )[
$(“button”).click(function( )[
$(“.test”).hide( );
});
});
</script>
</head>
<body>
12
Advanced Java Script
Output: When a user clicks on a button, the element with class=“test” will be hidden
This is a heading This is a paragraph
This is another paragraph.
Click me
Click me
<script>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“*”).hide( );
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p> This is a paragraph.</p>
<p> This is another paragraph.</p>
<button>Click me</button>
</body>
</html>
Output: When a user clicks on a button, all elements will be hidden including click me
This is a heading
This is another paragraph.
Click me
13
Advanced Java Script
<!DOCTYPE html>
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script>
<script>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“p, #test, .id”).css(“background-color”, “yellow”):
;
});
});
</script>
</head>
<body>
<h2 class=id> This is a heading </h2>
<p> This is a paragraph.</p>
<button>Click me</button>
</body>
</html>
Output: When a user clicks on a button, the selected elements will be applied yellow color
background
This is a hedaing This is a heading
This is a paragraph. This is a paragraph
This is another paragraph.
Click me
Click me
14
Advanced Java Script
When this method is used to set attribute values, it sets one or more attribute/value pairs for the
set of matched elements.
Syntax:
Return the value of an attribute: $(selector).attr(attribute)
Set the attribute and value: $(selector).attr(attribute, value)
Set attribute and value using a function:$(selector).attr(attribute,function(index,currentvalue))
Set multiple attributes and values: $(selector).attr({attribute:value,attribute:value,….})
Example:
Set the width attribute of an image:
$(“button”).click(function( ){
$(“img”).attr(“width,”, “500”);
});
15
Advanced Java Script
Applying styles:
The addClass(classes) method can be used to apply defined style sheets onto all the
matched elements. You can specify multiple classes separated by space.
Example:
Following is a simple example which set src attribute of an image tag to a correct location.
<html>
<head>
<title> The title</title>
<script type=“text/javascript” src=“/jquery/jquer-1.3.2.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( ){
$(“em”).addclass(“selected”);
$(“myid”).addclass(“highlight);
});
</script>
<style>
.selected {color:red;}
.highlight{background:yellow;}
</style>
</head>
<body>
<em title=“Bold and Brave”> This is first paragraph.</em>
<p id=“myid”> This is second paragraph.</p>
</body>
</html>
Q5. List out methods to manipulate JQuery DOM attributes and describe them with suitable
examples.
Methods to manipulate DOM attributes and properties:
Methods Description
attr(properties) Set a key/value object as properties to all matched elements.
attr(key, fn) Set a single property to a complete value, on all matched elements.
removeAttr(name) Remove an attribute from each of the matched elements.
hasClass(class) Returns true if the, specified class is present on at least one of the set of
matched elements.
removeClass(class Remove all or the specified class(es) form the set of matched elements.
)
toggleClass(class) Adds the specified class if it is not present, removes the specified class if it is
16
Advanced Java Script
present
html( ) Get the html contents (inner html) of the first matched element.
html(val) Set the html contents of every matched elements.
text( ) Get the combined text contents of all matched elements.
text(val) Set the text contents of all matched elements.
val( ) Get the input value of the first matched element.
val(val) Set the value attribute of every matched element if it is called on <input> but
if it is called on <select> with the passed <option> value then passed option
would be selected, if it is called on check bor or radio box then all the
matching check box and radiobox would be checked.
Examples:
(1) $(“#myID”).attr(“custom”):
It returns a value of attribute custom for the first element matching with ID myID.
It sets the alt attribute of all the images to a new value “sample image”.
It sets the value of all <input> elements to the empty string, as well as sets the title to the
string please enter a value.
It selects all links with an href attribute starting with http:// and set its target attribute to
_blank
(5) $(“a”).removeAttr(“target”) :
It modifies the disabled attribute to the value “disabled” while clicking submit button.
(7) $(“p.text”).hasClass(“selected”):
(8) $(“p”).text( ):
Return string that contains the combined text contents of all matched <p> elements.
17
Advanced Java Script
This would set “<i>Hello World<i>” as text content of the matching <p> elements.
(10) $(“p”).html( ):
This would set the HTML content of all matching <div> to Hello World.
(12) $(“input:checkbox:checked”).val( ):
(13) me=bar]:checked”).val( ):
(14) $(“button”).val(“Hello”):
(15) $(“input”).val(“on”):
This would check all the radio or check box button whose value is “on”.
This would select Orange and Mango options in a dropdown box with options Orange,
Mango and Banana.
18
Advanced Java Script
The index numbers start at 0, so the first element will have the index number 0 (not 1).
Syntax
$(selector).eq(index)
Example: adds the color to second list item.
<html>
<head>
<title>The Title</title>
<script type=“text/javascript” src=“/jquery/jquery-1.3.2.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( ){
$(“li”).eq(2).addclass(“selected”);
});
</script>
<style>
.selected{color:red;}
</style>
</head>
<body>
<div>
<ul>
<li> list item 1</li>
<li> list item 2</li>
<li> list item 3</li>
<li> list item 4</li>
<li> list item 5 </li>
<li> list item 6 </li>
</ul>
</div>
</body>
</html>
Syntax
$(selector).filter(criteria, function(index))
Example: adds color to the lists associated with middle class
19
Advanced Java Script
<html>
<head>
<title> The Title</title>
<script type=“text/javascript” src=“/jquery/jquery-1.3.2.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( ){
$(“li”).filter(“.middle”).addclass(“selected”);
});
</script>
<style>
.selected {color:red;}
</style>
</head>
<body>
<div>
<ul>
<li class=“top”> list item 1 </li>
<li class=“top”> list item 2 </li>
<li class=“middle”> list item 3 </li>
<li class=“middle”> list item 4 </li>
<li class=“bottom”> list item 5 </li>
<li class=“bottom”> list item 6 </li>
</ul>
</div>
</body>
</html>
20
Advanced Java Script
$(“p”).find(“span”).addclass(“selected”);
});
</script>
<style>
.selected{ color:red; }
</style>
</head>
<body>
<p> This is 1st paragraph and <span> THIS IS RED </span> </p>
<p> This is 2nd paragraph and <span> THIS IS ALSO RED</span> </p>
</body>
</html>
Q7. List out JQuery DOM Traversing Methods and describe them.
Methods used to filter out various elements from a list of DOM elements.
Selector Description
eq(index) This reduces the set of matched elements to a single element.
filter(selector) This removes all the elements from the set of matched elements that do not
match the specified selector(s).
filter(fn) This removes all the elements from the set of matched elements that do not
match the specified functions.
is(selector) It checks the current selection against an expression and returns true, if at
least one element of the selection fits the given selector.
map(callback) It translate a set of elements in the JQuery object onto another set of values in
a JQuery array(which may, or may not contain elements).
not (selector) This removes the elements matching the specified selector from the set of
matched elements.
slice(start, [end]) It selects a subset of the matched elements.
Selector Description
add(selector) Adds more elements, matched by the given selector, to the set of matched
elements.
andSelf( ) Add the previous selection to the current selection.
children ([selector]) Get a set of elements containing all of the unique immediate children of
each of the matched set of elements.
21
Advanced Java Script
closest(selector) Get a set of elements containing the closest parent element that matches the
specified selector, the starting element included.
contents( ) Find all the child nodes inside the matched elements (including text nodes),
or the content document, if the element is an iframe.
end( ) Revert the most recent ‘destructive’ operation, changing the set of matched
elements to its previous state.
find (selector) Searches for descendent elements that match the specifies selectors.
next( [selector]) Get a set of elements containing the unique next siblings of each of the given
set of elements.
nextAll( [selector]) Find all sibling elements after the current element.
offsetParent( ) Returns a JQuery collection with the positioned parent of the first matched
element.
parent( [selector]) Get the direct parent of an element. If called on a set of elements, parent
returns a set of their unique direct parent elements.
parents( [selector]) Get a set of elements containing the unique ancestors of the matched set of
elements (except for the root element).
prev( [selector]) Get a set of elements containing the unique previous siblings of each of the
matched set of elements.
prevAll( [selector]) Find all sibling elements in front of the current element.
siblings( [selector]) Get a set of elements containing all of the unique siblings of each of the
matched set of elements.
22
Advanced Java Script
2. 120.27
3. 0.26
(c) Boolean: A Boolean in JavaScript can be either true or false. If a number is zero, it defaults to
false. If an empty string defaults to false:
Following are the valid examples of a JavaScript Boolean:
1. true //true
2. false //false
3. 0 //false
4. 1 //true
5. “ ” //false
6. “hello” //true
(d) Objects: An object can be created using the object literal as follows:
var emp={
name: “zara”,
age: 10
};
Write and read properties of an object can be done using he dot notations as follows:
//getting object properties
Emp.name //zara
Emp.age //10
23
Advanced Java Script
1. Ease of use: It is easy to use compared to standard javascript and other javascript
libraries. Apart from simple syntax, it also requires much less lines of code to achieve
the same feature in comparison.
2. Large library: JQuery enables you to perform hordes of functions in comparison to
other JavaScript libraries.
3. Strong opensource community. (Several JQuery plugins available): JQuery, while
relatively new, has a following that religiously devote their time to develop and enhance
the functionality of JQuery. Thus there are hundreds of prewritten plugins available for
download to instantly speed up your development process. Another advantage behind
this is the efficiency and security of the script.
4. Great documentation and tutorials: The JQuery website has a comprehensive
documentation and tutorials to get even an absolute beginner in programming to get
the ball rolling with this library.
5. Ajax support: JQuery lets you develop Ajax templates with ease, Ajax enables a sleeker
interface where action can be performed on pages without requiring the entire page to
be reloaded. A pretty but simple example of this can be seen above the fold on how to
refinance your mortgage.net.
Disadvantages:
24
Advanced Java Script
Unit – II
JQuery – CSS Methods
Essay Questions
Q.1. How to apply and return CSS properties using JQuery CSS Methods. Explain with an example.
JQuery CSS Methods:
JQuery CSS method css( ) is used to apply one or more(multiple) CSS properties on DOM elements.
It is also used to return style properties for the selected elements.
(i) Applying a single CSS property: JQuery CSS method can apply single CSS property on the
selected element as follows:
selector.css(“PropertyName”, “PropertyValue”);
Here property name can be a javascript string, and based on its value, property value could
be string or integer.
Example:
$(“p”).css(“background-color”, “yellow”); will apply background color value yellow for all the
elements with tag name <p> in the document.
<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( )
{
$(“p”).css(“background-color”, “yellow”):
});
</script>
</head>
<body>
<div>
<p> This is a Paragraph. </p>
</div>
</body>
</html>
Output:
This is a Paragraph
25
Advanced Java Script
(ii) Applying multiple CSS properties: JQuery CSS method can apply multiple CSS properties on
the selected element as follows:
selector.css({“PropertyName”, “PropertyValue”, “PropertyName”, “PropertyValue”, …..});
Example:
$(“p”).css({“background-color”: “yellow”, “color”:“red” }); will apply background color
value yellow and font color value red for all the elements with tag name <p> in the document.
<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( )
{
$(“p”).css({“background-color”:“yellow”, “color”: “red”});
});
</script>
</head>
<body>
<div>
<p> This is a Paragraph. </p>
</div>
</body>
</html>
Output:
This is a Paragraph
(iii) Return CSS properties: JQuery CSS method can also return CSS properties applied on the
selected element as follows:
alert(selector.css(“PropertyName”));
Example:
alert($(“p”).css(“background-color”)); will return background color value yellow
RGB(255, 255, 0) for the first element with tag name <p> in the document.
<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
26
Advanced Java Script
Q.2. List out JQuery dimension methods and display all the dimensions using related methods.
JQuery Dimension Methods:
JQuery CSS methods that are used for working with dimensions are called JQuery dimension
methods.
JQuery Dimension
S.No. Description
Method
1. width( ) Sets or return the width of an element (excludes padding, border and
margin).
2. height( ) Sets or returns the height of an element (excludes padding, border
and margin).
3. innerWidth( ) Returns the width of an element (includes padding).
4. innerHeight( ) Returns the height of an element (includes padding).
5. outerWidth( ) Returns the width of an element (includes padding and border).
6. outerHeight( ) Returns the height of an element (includes padding and border).
7. outerWidth(true) Returns the width of an element (includes padding, border and
margin).
8. outerHeight(true) Returns the height of an element (includes padding, border and
margin).
27
Advanced Java Script
Margin
Border
Padding
outerHeight(true)
outerHeight( )
innerHeight( )
Element
height( )
Width( )
innerWidth( )
outerWidth( )
outerWidth(true)
28
Advanced Java Script
});
});
</script>
<style>
#div1 {
height: 150px;
width: 300px;
padding: 10px;
margin: 3px
border: 1px solid blue;
background-color: lightblue;
}
</style>
</head>
<body>
<div id=“div1”> </div>
<br>
<button>Display dimensions of div</button>
</body>
</html>
Output:
Width of div: 300
Height of div: 150
Inner width of div: 320
Inner height of div: 170
Outer width of div (margin included): 322
Outer height of div (margin included): 172
Outer width of div (margin included):328
Outer height of div (margin included): 178
Display
Display dimensions
dimensions of
of div
div Display
Display dimensions
dimensions of
of div
div
Q.3. How to set and return element width in JQuery. Explain with an example.
Margin
Border
Padding
Element
Width( )
29
Advanced Java Script
30
Advanced Java Script
Set
Set width
width of
of div
div to
to 500px
500px Set
Set width
width of
of div
div to
to 10em
10em Set
Set width
width of
of div
div to
to 300pt
300pt Decrease
Decrease width
width of
of div
div with
with 200
200
alert(selector.width( ));
Example:
This will returns the width of selected element in an alert box and also returns the width of current
window and current document.
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function( ){
$(“button”).click(function( ) {
alert(“Width of div:” + $(“div”).width( ));
$(“#span1”).text($(window).width( ) );
$(“#span2”).text($(document).width( ) );
});
});
</script>
</head>
<body>
<p>The width of this window is <span id= “span1”> unknown</span>px.</p>
<p>The width of this document is <span id= “span2”> unknown</span>px.</p>
<button> Display the width of div, window and document </button>
<div style= “height:100px; width:300px; border:1px solid blue; background-color: lightblue;”>
</div><br>
</body>
</html>
31
Advanced Java Script
Q.4. How to set and return element height in JQuery. Explain with an example.
Margin
Border
Padding
Element
height( )
(i) Setting Element height: When this method is used to set element height, it sets the height of
ALL matched elements using the syntax.
Selector.height(value);
32
Advanced Java Script
Set
Set height
height of
of div
div to
to 500px
500px Set height of
Set height of div
div to
to 10em
10em Set height of
Set height of div
div to
to 300pt
300pt increase height of
increase height of div
div with
with 200
200
(ii) Return Element Height: When this method is used to return element height, it returns the
height of FIRST matched elements using the syntax.
alert(selector.height( ));
Example: This will returns the height of selected element in an alert box and also returns the
height of current window and current document.
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function( ){
33
Advanced Java Script
$(“button”).click(function( ) {
alert(“height of div:” + $(“div”).height ( ));
$(“#span1”).text($(window).height ( ) );
$(“#span2”).text($(document).height( ) );
});
});
</script>
</head>
<body>
<p>The height of this window is <span id= “span1”> unknown</span>px.</p>
<p>The height of this document is <span id= “span2”> unknown</span>px.</p>
<button> Display the height of div, window and document </button>
<div style= “height:100px; width:300px; border:1px solid blue; background-color: lightblue;”>
</div><br>
</body>
</html>
Q.5. Explain in detail about DOM Content manipulation in JQuery with an example.
Content Manipulation: DOM elements content can be manipulated using
1. html( ); 2. text( )
1. html() method: The html() method sets or returns the content (inner HTML – text + HTML
markup) of the selected elements.
(i) Set Content: When this method is used to set content, it overwrites the content of ALL matched
elements using the syntax
Selector.html(“content”);
Example: $(“p”).html(“<b> Content modified</b>”); will change the content of all the elements
with tag name <p> and in the document bolds it.
<html>
<head>
<title> The JQuery Example </title>
34
Advanced Java Script
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“p”).html(“<b>Content modified</b>”):
});
});
</script>
</head>
<body>
<p>Given content.</p>
<button> Change content of all p elements</button>
</body>
</html>
Output:
Given content. Content modified
Change
Change content
content of
of all
all p
p elements
elements Change
Change content
content of
of all
all p
p elements
elements
(ii) Return Content: When this method is used to return content, it returns the content of FIRST
matched elements using the syntax
alert(selector.html( ) );
Example: alert($(“p”).html( )); will return the content of all the elements with tag name<p> in the
document.
<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( ){
$(“button”).click(function( ){
alert($(“p”).html( )):
});
});
</script>
</head>
35
Advanced Java Script
<body>
<p>content<b>displayed</b> in alert box.</p>
<button>Return content of all p elements</button>
</body>
</html>
Output:
2. text( ) method: The text( ) method sets or returns the text content of the selected elements.
(i) Set Content: When this method is used to set content, it overwrites the content of ALL matched
elements using the syntax.
selector.text(“content”);
Example: $(“p”).text(“<b>Content modified</b>”); will change the content of all the elements
with tag name <p> in the document but bolding will not be applied.
<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( )
{
Alert($(“p”).css(“background-color”)):
});
</script>
</head>
<body>
<p>Given content.</p>
<button> Change content of all p elements</button>
</body>
</html>
Output:
Given content. Content modified
Change
Change content
content of
of all
all p
p elements
elements Change
Change content
content of
of all
all p
p elements
elements
36
Advanced Java Script
(ii) Return Content: When this method is used to return content, it returns the content of
FIRST matched elements using the syntax
selector.text( );
Example: alert($(“p”).text( )); will return the content of all the elements with tag name <p> in the
document but discards <b> and </b> elements in <p>.
<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( ){
$(“button”).click(function( ){
alert($(“p”).html( ));
});
});
</script>
</head>
<body>
<p>content<b>displayed</b> in alert box</p>
<button>Return content of all p elements</button>
</body>
</html>
Output:
Content displayed in alert box. X
Q.6. Explain in detail about DOM Element Replacement in JQuery with an example.
Replacing DOM Element: DOM elements content can be manipulated using
1. replaceAll( )
2. replaceWith( )
1. replaceAll( ) method: The replaceAll( ) method replaces selected elements with new
HTML elements using the syntax
37
Advanced Java Script
$(content).replaceAll(“selector”);
<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“<h2>Hello world!</h2>”).replaceAll(“p”);
});
});
</script>
</head>
<body>
<p>content in first paragraph.</p>
<p>content in second paragraph.</p>
<button>replace content of all p element</button>
</body>
</html>
Output:
Hello world!
content in first paragraph
content in second paragraph Hello world!
2. replaceWith( ) method: The replaceWith( ) method replaces selected elements with new
content using the syntax
selector.replaceWith(“content”);
Example: $(“p:first”).replaceWith(“<h1>Hello world!</h1>”); will replace the content of first
element with tag name <p> in the document.
<html>
<head>
38
Advanced Java Script
Output:
content in first paragraph
Hello world!
content in second paragraph
Content in second paragraph
replace content of first p elements
2. detach( )
3. empty( )
1. remove( ) method: The remove( ) method removes the selected elements, including all
text and child nodes. This method also removes data and events of the selected elements.
selector.remove( );
39
Advanced Java Script
<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<body>
<p>Click on any square below:</p>
<span id= “result”></span>
Output:
Click on any square below: Click on any square below: Click on any square below: Click on any square below:
2. detach( ) method: The detach( ) method removes the selected elements, including all text
and child nodes. This method keeps data and events of the selected elements.
selector.detach( );
Example: $(this).detach( ); will remove the selected one.
<html>
40
Advanced Java Script
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function( ) {
$(“div”).click(function( ) {
$(this).detach( );
});
});
</script>
<body>
<p>Click on any square below:</p>
<span id= “result”></span>
Output:
Click on any square below: Click on any square below: Click on any square below: Click on any square below:
3. empty( ) method: The empty( ) method removes only the content from the selected
elements.
selector.empty( );
Example: $(this).empty( ); will remove the content of selected one but background remains same.
<html>
<head>
<title> The JQuery Example </title>
41
Advanced Java Script
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<body>
<p>Click on any square below:</p>
<span id= “result”></span>
Output:
Click on any square below: Click on any square below: Click on any square below: Click on any square below:
2. before( )
3. append( )
4. appendTo( )
5. prepend( )
6. prependTo( )
7. insertAfter( )
42
Advanced Java Script
8. insertBefore( )
1. after( ) method: The after( ) method inserts specified content after the selected elements.
selector.after(content);
Example: $(“p”).after(“<p>Hi students</p>”); will insert content after <p> content in <body>
section
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”> </script>
<script>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“p”).after(“<p>Hi students</p>”);
});
});
</script>
</head>
<body>
<button>Insert content after each p element</button>
<p> How are you </p>
</body>
</html>
Output:
Insert
Insert content
content after
after each
each p
p element
element Insert
Insert content
content after
after each
each p
p element
element
Hi students
2. before( ) method: The before( ) method inserts specified content after the selected
elements.
selector.before(content);
Example: $(“p”).before(“<p>Hi students</p>”); will insert content after <p> content in <body>
section
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”> </script>
43
Advanced Java Script
<script>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“p”).before(“<p>Hi students</p>”);
});
});
</script>
</head>
<body>
<button>Insert content before each p element</button>
<p> How are you </p>
</body>
</html>
Output:
Insert
Insert content
content before
before each
each p
p element
element Insert
Insert content
content before
before each
each p
p element
element
3. append( ) method: The append( ) method inserts specified content at the end of the
selected elements.
selector.append(content)
Example: $(“p”).append(“?”); will insert? at the end of <p> content in <body> section.
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”> </script>
<script>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“p”).append(“?”);
});
});
</script>
</head>
<body>
<button>Insert content at the end</button>
44
Advanced Java Script
45
Advanced Java Script
Output:
4. appendTo( ) method: The appendTo( ) method inserts HTML elements at the end of the
selected elements.
$(content).appendTo(selector);
Example: $(“<li>?</li>”).appendTo(“ol”); will append? to <ol> content in <body> section
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”> </script>
<script>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“<li>?</li>”).appendTo(“ol”);
});
});
</script>
</head>
<body>
<ol>
<li> List item 1</li>
<li> List item 2</li>
<li> List item 3</li>
</ol>
<button>Append content at the end of ol element</button>
</body>
</html>
Output:
46
Advanced Java Script
5. prepend( ) method: The prepend( ) method inserts specified content at the beginning of
the selected elements.
selector.prepend(content);
Example: $(“p”).prepend(“Hi,”); will insert ? ? to <ol> content in <body> section
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”> </script>
<script>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“p”).prepend(“Hi,”);
});
});
</script>
</head>
<body>
<button>Insert content at the beginning </button>
<p> How are you </p>
</body>
</html>
Output:
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”> </script>
<script>
$(document).ready(function( ){
47
Advanced Java Script
$(“button”).click(function( ){
$(“<li>?</li>”).prependTo(“ol”);
});
});
</script>
</head>
<body>
<ol>
<li> List item 1</li>
<li> List item 2</li>
<li> List item 3</li>
</ol>
<button>Append content at the beginning of ol element</button>
</body>
</html>
Output:
1. List item 1 1. ?
2. List item 2 2. List item 1
3. List item 3 3. List item 2
4. List item 3
Append content at the Append content at the
beginning of ol element beginning of ol element
7. insertAfter( ) method: The insertAfter( ) method inserts HTML elements after the selected
elements.
$(content).insertAfter(selector);
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”> </script>
<script>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“<li>?</li>”).insertAfter(“ol”);
});
48
Advanced Java Script
});
</script>
</head>
<body>
<ol>
<li> List item 1</li>
<li> List item 2</li>
<li> List item 3</li>
</ol>
<button>Append content after ol element</button>
</body>
</html>
Output:
8. insertBefore( ) method: The insertBefore( ) method inserts HTML elements before the
selected elements.
$(content).insertBefore(selector);
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”> </script>
<script>
$(document).ready(function( ){
$(“button”).click(function( ){
$(“<li>?</li>”).insertBefore(“ol”);
});
});
</script>
</head>
<body>
49
Advanced Java Script
<ol>
<li> List item 1</li>
<li> List item 2</li>
<li> List item 3</li>
</ol>
<button>Append content before ol element</button>
</body>
</html>
Output:
1. List item 1 ?
2. List item 2 1. List item 1
3. List item 3 2. List item 2
3. List item 3
Append content before ol element
Append content before ol element
Q.9. List out various types of DOM events in JQuery and describe them.
Types of events: 1) Mouse Events, 2) Keyboard Events, 3) Form Events,
4) Document/Window Events.
50
Advanced Java Script
Q.10. How to establish event handlers on DOM elements in JQuery. Explain with an example.
Binding Event handlers: The bind( ) method attaches one or more event handlers for selected
elements, and specifies a function to run when the event occurs.
(i) Attaching a single event:
selector.bind(event, data, function, map);
Example: $(“p”).click( ); assigns a bind event to all elements with tag name <p> in the document.
Now, a function is to be passed to the event to define what should happen when the event fires.
$(“p”).click(function( ) {
//action goes here!!
});
Here $(“p”).bind(“click”, function( ){}); attaches click event to the elements with tag name <p> in
the document.
<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
51
Advanced Java Script
Output:
click me X
(ii) Attaching multiple events: Multiple event values are separated by space.
selector.bind(“event event”, data, function, map);
Example: Here $(“p”).bind(“mouseover mouseout”, function( ){}); attaches multiple
(mouseover, mouseout) event to the elements with tag name <p> in the document.
<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
Output: When placed mouse on the paragraph, it changes to red color, when removed changes to
black.
Place mouse here and move out Place mouse here and move out
52
Advanced Java Script
Example: $(“button”).bind({…}); attaches events click, mouseover, mouseout using event map to
the selected elements in the document.
<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
Output: when placed mouse on the click me, background changes to red color, when removed
changes to blue and when “click me!” button is clicked, it hides the statement click me and when
again clicked it displays the statement.
53
Advanced Java Script
(iv) Using data while attaching events: This field is optional and specifies additional data to pass
along to the function.
selector.bind(event, data, function, map);
Example: $(“button”).bind({…..}); attaches click event to the elements with tag name <p> in the
document and additional data {msg: “You just clicked me!”}
<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
Output:
Q.11. How to remove event handlers that are established on DOM elements in JQuery. Explain with
an example.
Unbinding Event handlers: The unbind() method removes event handlers from selected elements.
This method can remove all or selected event handlers, or stop specified functions from running
when the event occurs.
54
Advanced Java Script
This method can also unbind event handlers using an event object. This is used to unbind an event
from within itself (like removing an event handler after the event has been triggered a certain
number of times).
Note: If no parameters are specified, the unbind() method will remove ALL event handlers from the
specified element.
(i) Removing event handler:
selector.unbind(event, function, eventobj);
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).unbind(); removes the click event on elements with tag name <p>.
<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
Output: in first case on clicking “click me.” it will be hided, but in second case on clicking click me!
to remove button, toggle effect will be removed and even on clicking “click me.” it will not
hide.
55
Advanced Java Script
(ii) Removing a specific function: unbind a specific function from a specified event for an
element.
selector.unbind(event, function, eventobj);
Example: Here $(“p”).unbind(“click”, alertMe); removes alertMe function specified along with
click event to the elements with tag name <p> in the document.
<html>
<head>
<title> The JQuery Example </title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script>
<script>
function alertMe() {
alert(“Hello World!”);
}
$(document).ready(function(){
$(“p”).click(alertMe);
$(“button”).click(function(){
$(“p”).unbind(“click”, alertMe);
});
});
</script>
</head>
<body>
<p> This is a paragraph.</p>
<p> This is another paragraph.</p>
<p>Click any p element to trigger an alert box.</p>
<button>Remove the alert box function from the click event for the p elements</button>
</body>
</html>
Output: in first case, on clicking any of 3 statements, alert box is displayed, but in second case on
clicking remove the alert box button, alertbox effect-on click event will be removed and even on
clicking the statements it will not display alert box.
56
Advanced Java Script
(iii) Unbinding an event handler using an event object: Specifies an event object to remove.
selector.unbind(event, function, eventobj);
Example: $(this).unbind(event); removes event function specified along with click event to the
elements with tag name <p> in the document when x>=2.
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”> </script>
<script>
$(document).ready(function(){
var x=0;
$(“p”).click(function(event){
$(“p”).animate({fontSize:”+=5px”});
x++;
if(x>=2){
$(this).unbind(event);
}
});
});
</script>
</head>
<body>
<p style= “font-size:20px;”>Click this p element to increase its size.</p><br>
<p style= “font-size:20px;”>The size can only be increased 2 times.</p>
</body>
</html>
Output: after clicking 2 times, the statements will not increase their size.
Click this p element to increase its size. Click this p element to increase its size.
The size can only be increased 2 times.
Q.12. Explain how to hide and show the elements in JQuery with an example.
57
Advanced Java Script
(i) hide() and show(): hide() is similar to the CSS property “display:none” and hidden elements
will not be displayed at all (no longer affects the layout of the page).
The hide() method hides the selected elements using the syntax
selector.hide(speed, easing, callback);
The show() method shows the hidden, selected elements using the syntax
selector.show(speed, easing, callback);
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).hide(); hides the elements with tag name <p> on clicking Hide button.
$(“p”).show(); shows all the hidden elements with tag name <p> on clicking Show
button.
<html>
<head>
<title>The JQuery Example</title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).hide();
});
$(“.btn2”).click(function(){
$(“p”).show();
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>Hide</button>
<button class=“btn2”>Show</button>
</body>
</html>
Output:
This is a paragraph.
Hide Show
58
Advanced Java Script
(ii) hide() and show() using speed parameter: It is optional and it specifies the speed of the hide
effect. Default value is 400 milliseconds
Possible values are
(a) milliseconds; (b) “slow”; (c) “fast”.
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).hide(1000); hides the elements with tag name <p> in 1000 milliseconds on
clicking Hide button.
$(“p”).show(1000); shows all the hidden elements with tag name <p> in 1000
milliseconds on clicking Show button.
<html>
<head>
<title>The JQuery Example</title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).hide(1000);
});
$(“.btn2”).click(function(){
$(“p”).show(1000);
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>Hide</button>
<button class=“btn2”>Show</button>
</body>
</html>
(iii) hide() and show() using callback parameter: It is optional and it specifies a function that is
to be executed after the hide() method is completed.
59
Advanced Java Script
JavaScript statements are executed line by line. However, with effects, the next line of code can be
run even though the effect is not finished. This can create errors. To prevent this, a callback function
is created.
A callback function is executed after the current effect is finished.
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).hide(1000, function(){}); hides the elements with tag name <p> in 1000
milliseconds on clicking Hide button and after hide effect is completed alert msg occurs.
$(“p”).show(1000, function(){}); shows all the hidden elements with tag name <p> in
1000 milliseconds on clicking Show button and after show effect is completed alert msg
occurs.
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).hide(1000, function(){
alert(“Hide() method is finished!”);
});
$(“.btn2”).click(function(){
$(“p”).show(1000, function(){
alert(“Show() method is finished!”);
});
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>Hide</button>
<button class=“btn2”>Show</button>
</body>
</html>
Output:
60
Advanced Java Script
(iv) hide() and show() using easing parameter: It is optional and it specifies the speed of the
element in different points of the animation. Default value is “swing”.
Possible values are : (a) “swing”; (b) “linear”
Toggle between hide() and show(): The toggle() method toggles between hide() and show() for
the selected elements.
This method checks the selected elements for visibility. Shows if an element is hidden and hides if
an element is visible this creates a toggle effect.
The toggle() method toggles using the syntax
selector.toggle(speed, easing, callback);
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).hide(); hides the elements with tag name <p> on clicking Hide button.
$(“p”).show(); shows all the hidden elements with tag name <p> on clicking Show button.
Whereas $(“p”).toggle(1000, function(){}); shows all the elements when hidden and hides when
they are visible on clicking toggle button and after toggle effect is completed alert msg occurs.
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).toggle(1000, function(){
alert(“Toggle() method is finished!”);
});
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
61
Advanced Java Script
Output:
Q.13. Explain how to apply slide effect for the elements in JQuery with an example.
Sliding effect: JQuery slide methods used to create sliding effect on elements are (1) slideUp(),
(2) slideDown(), (3) slideToggle().
The slideUp() method slides-up(hides) the selected elements using the syntax
selector.slideup(speed, easing, callback);
The slideDown() method slides-down (shows) the selected elements using the syntax
Selector.slideDown(speed, easing, callback);
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).slideUp(); hides the elements with tag name <p> on clicking slideUp button.
$(“p”).slideDown(); shows all the hidden elements with tag name <p> on clicking slideDown button.
<html>
<head>
<title>The JQuery Example</title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).slideUp();
});
62
Advanced Java Script
$(“.btn2”).click(function(){
$(“p”).slideDown();
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>Slide up</button>
<button class=“btn2”>Slide down</button>
</body>
</html>
(i) slideUp() and slideDown() using speed parameter: It is optional and it specifies the speed of
the slide effect. Default value is 400 milliseconds
Possible values are (a) milliseconds; (2) “slow”; (3) “fast”.
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).slideUp(1000); hides the elements with tag name <p> in 1000 milliseconds on
clicking SlideUp button.
$(“p”).slideDown(1000); shows all the hidden elements with tag name <p> in 1000
milliseconds on clicking SlideDown button.
<html>
<head>
<title>The JQuery Example</title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).slideUp(1000);
});
$(“.btn2”).click(function(){
$(“p”).slideDown(1000);
});
});
63
Advanced Java Script
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>Slide up</button>
<button class=“btn2”>Slide down</button>
</body>
</html>
(ii) slideUp() and slideDown() using callback parameter: It is optional and it specifies a
function that is to be executed after the slideUp() is completed or slideDown() method is
completed.
JavaScript statements are executed line by line. However, with effects, the next line of code can be
run event though the effect is not finished. This can create errors. To prevent this, a callback
function is created.
A callback function is executed after the current effect is finished.
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).slideUp(1000, function(){}); hides the elements with tag name <p> in 1000
milliseconds on clicking Hide button and after slideup effect is completed alert msg
occurs.
$(“p”).slideDown(1000, function(){}); shows all the hidden elements with tag name
<p> in 1000 milliseconds on clicking Show button and after slidedown effect is
completed alert msg occurs.
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).slideUp(1000, function(){
alert(“SlideUp() method is finished!”);
});
});
$(“.btn2”).click(function(){
$(“p”).slideDown(1000, function(){
64
Advanced Java Script
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>Slide up</button>
<button class=“btn2”>Slide Down</button>
</body>
</html>
(iii) slideToggle(); The toggle() method toggles between slideUp() and slideDown() for the
selected elements.
This method checks the selected elements for visibility. Slides down if an element is hidden and
slides up if an element is visible – this creates a toggle effect.
The toggle() method toggles using the syntax
selector.slidetoggle(speed, easing, callback);
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).slideToggle(1000, function(){}); shows all the elements when hidden and hides
when they are visible on clicking toggle button and after toggle effect is completed alert
msg occurs.
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).slideToggle(1000, function(){
alert(“Hide() method is finished!”);
});
});
65
Advanced Java Script
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>Toggle Up and Toggle Down</button>
</body>
</html>
Q.14. Explain how to apply fade effect for the elements in JQuery with an example.
JQuery fade methods used to fade elements in and out of visibility are
(1) fadeIn (2) fadeOut() (3) fadeToggle() (4) fadeTo()
(1) fadeIn() and fadeout(): The fadeIn() method gradually changes the opacity, for selected
elements, from hidden to visible (fading effect) using the syntax
selector.fadein(speed, easing, callback);
The fadeOut() method gradually changes the opacity, for selected elements, from visible to hidden
(fading effect) using the syntax
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).fadeIn(); hides the elements with tag name <p>.
$(“p”).fadeOut(); shows all the hidden elements with tag name <p>.
<html>
<head>
<title>The JQuery Example</title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).fadeIn();
});
$(“.btn2”).click(function(){
$(“p”).fadeOut();
});
66
Advanced Java Script
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>fade in</button>
<button class=“btn2”>fade out</button>
</body>
</html>
(i) fadeIn() and fadeOut() using speed parameter: It is optional and it specifies the speed of the
fade effect. Default value is 400 milliseconds
Possible values are (a) milliseconds; (b) “slow”; (c) “fast”.
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).fadeIn(1000); hides the elements with tag name <p> in 1000 milliseconds.
$(“p”).fadeOut(1000); shows all the hidden elements with tag name <p> in 1000 milliseconds.
<html>
<head>
<title>The JQuery Example</title>
<script type=“text/javascript”
src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).fadeIn(1000);
});
$(“.btn2”).click(function(){
$(“p”).fadeOut(1000);
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
67
Advanced Java Script
(ii) fadeIn() and fadeOut() using callback parameter: It is optional and it specifies a function
that is to be executed after the fadeIn() is completed or fadeOut() method is completed.
JavaScript statements are executed line by line. However, with effects, the next line of code can be
run even though the effect is not finished. This can create errors. To prevent this, a callback function
is created.
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).fadeIn(1000, function(){}); hides the elements with tag name <p> in 1000 milliseconds
and after fadeIn effect is completed alert msg occurs.
$(“p”).fadeOut(1000, function(){}); shows all the hidden elements with tag name <p> in 1000
milliseconds and after fadeOut effect is completed alert msg occurs.
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).fadeIn(1000, function(){
alert(“fadeIn() method is finished!”);
});
});
$(“.btn2”).click(function(){
$(“p”).fadeOut(1000, function(){
alert(“fadeOut() method is finished!”);
});
});
});
</script>
68
Advanced Java Script
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>fade in</button>
<button class=“btn2”>fade out</button>
</body>
</html>
(2) fadeToggle(): The toggle() method toggles between fadeIn() and fadeOut() for the selected
elements.
This method checks the selected elements for visibility. If an element is faded out, fadeToggle() will
fades them in and fades out if an element is faded in – This creates a toggle effect.
The toggle() method toggles using the syntax
selector.fadetoggle(speed, easing, callback);
Example: Here $(“p”).click(function(){}); attaches click event to the elements with tag name <p>
in the document.
$(“p”).slideToggle(1000, function(){}); shows all the elements when hidden and hides
when they are visible on clicking toggle button and after toggle effect is completed alert
msg occurs.
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).fadeToggle(1000, function(){
alert(“Hide() method is finished!”);
});
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>Toggle In and Toggle Out</button>
69
Advanced Java Script
</body>
</html>
(3) fadeTo(): The fadeTo() method gradually changes the opacity, for selected elements, to a
specified opacity (fading effect) using the syntax.
selector.fadeto(speed, opacity, easing, callback);
Specifies the opacity to fade to. Must be a number between 0.00 and 1.00
Example:
<html>
<head>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“.btn1”).click(function(){
$(“p”).fadeTo(1000, 0.2, function(){
alert(“FadeTo() method is finished!”);
});
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button class=“btn1”>Fade to</button>
</body>
</html>
Q.15. Explain how to apply custom animations for the elements in JQuery with an example.
The JQuery animate() method is used to create custom animations.
(1) Single property is animated using the syntax $(selector).animate({params}, speed, callback);
The required params parameter defines the CSS properties to be animated.
The optional speed parameter specifies the duration of the effect. It can take the following values:
“slow”, “fast”, or milliseconds.
The optional callback parameter is a function to be executed after the animation completes.
Example
<head>
70
Advanced Java Script
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“button”).click(function(){
$(“div”).animate({left: ‘250px’});
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the
position, remember to first set the CSS position property of the element to relative, fixed, or
absolute!</p>
<div style= “background:#98bf21;height:100px;width:100px;position:absolute;”> </div>
</body>
</html>
(3) Relative values (the value is then relative to the element’s current value) can be defined.
This is done by putting +=or -= in front of the value:
Example
$(“button”).click(function(){
$(“div”).animate({
left: ‘250px’,
height: ‘+=150px’,
width: ‘+=150px’
71
Advanced Java Script
});
});
Q.1. List out the JQuery CSS methods and describe them.
JQuery CSS Methods: The following table lists the JQuery CSS methods used to manipulate the
HTML and CSS.
Q.2. List out the JQuery DOM manipulation methods and describe them.
JQuery DOM Manipulation Methods:
The following table lists the JQuery DOM Manipulation methods used to manipulate DOM.
JQuery DOM
Manipulation Method Description
72
Advanced Java Script
Q.3. List out the JQuery Event Object methods and describe them.
JQuery Event Object Methods: The following table lists the JQuery Event Object methods which
can be called on an event object.
73
Advanced Java Script
Q.4. List out the JQuery Event Attributes and describe them.
JQuery Event Attributes: The following table lists the JQuery Event Attributes.
JQuery Attribute
Description
Method
1 event.data Contains the optional data passed to an event method when the
current executing handler is bound
2 event.pageX Returns the mouse position relative to the left edge of the document
3 event.pageY Returns the mouse position relative to the top edge of the document
4 event.screenX For mouse events, specifies the horizontal coordinate of the event
relative from the screen origin.
5 event.screenY For mouse events, specifies the vertical coordinate of the event
relative from the screen origin.
6 event.currentTarget The current DOM element within the event bubbling phase
7 event.delegateTarget Returns the element where the currently-called JQuery event
handler was attached
8 event.relatedTarget Returns which element being entered or exited on mouse
movement.
9 event.result Contains the last/previous value returned by an event handler
triggered by the specified event
1 event.target Returns which DOM element triggered the event
0
1 event.timeStamp Returns the number of milliseconds since January 1, 1970, when the
1 event is triggered
1 event.type Returns which event type was triggered (for example, click).
2
1 event.which Returns which keyboard key or mouse button was pressed for the
3 event (1 for left, 2 for middle, 3 for right).
1 Altkey Set to true if the Alt key was pressed when the event was triggered,
4 false if not. The Alt key is labeled Option on most Mac keyboards.
1 ctrlkey Set to true if the Ctrl key was pressed when the event was triggered,
5 false if not.
1 metakey Set to true if the Meta key was pressed when the event was
6 triggered, false if not. The Meta key is the Ctrl key on PCs and the
74
Advanced Java Script
Q.5. List out the JQuery effect methods and describe them.
JQuery Effect Methods: The following table lists the JQuery Effect Methods.
75
Advanced Java Script
76
Advanced Java Script
Unit – III
INTRO TO JQUERY UI
Essay Questions
(a) Custom Download: Click on this button to download a customized version of library.
(b) Stable: Click on this button to get the stable and latest version of JqueryUI library.
(c) Legacy: Click on this button to get the previous major release of the JqueryUI library.
77
Advanced Java Script
Using Download Builder, user can create a custom build to include only those portions of the library
that are in need. User can download this new customized version of JqueryUI, depending on the
chosen theme. The following screen appears. (See Page 75)
This is useful when you require only specific plugins or features of the JqueryUI library. The
directory structure of this version is shown in the following figure.
CSS
/ Ui –
lightness/
Image
s/
Jquery – ui
-1.10.4.custom.CSS
Jquery – ui
-1.10.4.custom.min.CSS
Development –
bundle/
Js/
Jquery-1.10.2.js
Jquery – ui
-1.10.4.custom.js
Jquery – ui
-1.10.4.custom.min.js
Index.html
Uncompressed files are located in the development – bundle directory. The uncompressed file is best
used during development or debugging; the compressed file saves bandwidth and improves
performance in production.
Stable download:
Click on the Stable button, which leads directly to a ZIP file containing the sources, examples, and
documentation for latest version of JqueryUI library. Extract the ZIP file contents to a jqueryui
directory.
This version contains all files including all dependencies, a large collection of demos, and even the
library’s unit test suite. This version is helpful to getting started.
Legacy downloads:
Click on the Legacy button, which leads directly to a ZIP file of previous major release of JqueryUI
library. This version also contains all files including all dependencies, a large collection of demos,
and even the library’s unit test suite. This version is helpful to get you started.
A CDN or Content Delivery Network is a network of servers designed to serve files to users. If user
uses a CDN link in your web page, it moves the responsibility of hosting files from user’s own
servers to a series of external ones. This also offers an advantage that if the visitor to that webpage
has already downloaded a copy of JqueryUI from the same CDN, it won’t have to be re-downloaded.
The JQuery Foundation, Google, and Microsoft all provide CDNs that host JQuery core as well as
JqueryUI, because a CDN does not require you to host your own version of JQuery and JqueryUI.
78
Advanced Java Script
The draggable (action, params) method can perform an action on the movable
elements, such as to prevent displacement. The actions which are nothing but
JQuery methods is specified as a string in the first argument and optionally, one or
more params can be provided based on the given action.
List of actions are:
destroy() option()
disable() option(options)
enable() option(optionName)
widget() option(optionName, Value)
droppable() It can be used in two forms:
accept greedy
activeClass hoverClass
addClasses scope
disabled tolerance
(d) $(selector, context).droppable(“action”, [params]) Method:
79
Advanced Java Script
80
Advanced Java Script
destroy() option()
disable() option(options)
enable() option(optionName)
widget() option(optionName, Value)
refresh()
It can be used in two forms:
(i) $(selector , context).sortable(options) Method:
The sortable (options) method declares that an HTML element contains
interchangeable elements. The options parameter is an object that specifies the
behavior of the elements involved during reordering.
List of options are:
appendTo() disabled helper ScrollSpeed
axis distance Items Tplerance
cancel dropOnEmpty Opacity z-index
containment forceHelperSize Placeholder
cursor forcePlaceholderSize Revert
Sortable() cursorAt Grid Scroll
delay handle ScrollSensitivity.
(j) $(selector, context).sortable (“action”, [params]) Method:
The sortable (action, params) method can perform an action on the sortable
elements, such as to prevent displacement. The action is specified as a string in the
first argument and optionally. One or more params can be provided based on the
given action.
List of actions are:
destroy() option() refresh()
disable() option(options) refreshPositions()
enable() option(optionName) toArray(options)
widget() option(optionName, Value) Serialize (options)
cancel()
81
Advanced Java Script
disabled icons
(b) $(selector, context).accordion(“action”, [params]) Method:
The autocomplete (“action”, params) method can perform an action on the list of
suggestions, such as show or hide. The action is specified as a String in the first
argument (e.g., “close” to hide the list).
The button (“action”, params) method can perform an action on buttons, such as
disabling the button. The action is specified as a string in the first argument (e.g.,
82
Advanced Java Script
83
Advanced Java Script
Disabled Position
Icons Role
Menus
(k) $(selector, context).menu (“action”, [params]) Method:
The menu (“action”, params) method can perform an action on menu elements,
such as enabling/disabling the menu. The action is specified as a string in the
first argument (e.g., “disable” disables the menu).
List of action are:
Blur Enable option() nextPage
Collapse Expand option(options) Previous
collapseAll Focus option(optionName) previousPage
Destroy isFirstltem option(optionName, Value) Refresh
disable isLastltem Next widget
progressbar() It can be used in two forms:
(l) $(selector, context). progressbar (options) Method:
The progressbar (options) method declares that an HTML element can be
managed in the form of a progress bar. The options parameter is an object that
specifies the appearance and behavior of progress bars.
List of options are:
Disabled
Max
value
(m) $(selector, context).progressbar (“action”, [params]) Method:
The progressbar (“action”, params) method can perform an action on progress
bar, such as changing the percentage filled. The action is specified as a string in
the first argument (e.g., “value” to change the percentage filled).
List of actions are:
destroy() option() Value()
disable() option(options)
enable() option(optionName)
widget() option(optionName, Value)
84
Advanced Java Script
85
Advanced Java Script
Q.4. Explain about consuming JQuery plugins from third party websites with an example.
JQuery plugins require JQuery to be present on a page in order to load properly. It works
under normal circumstances, but when creating a third-party widget, it will not load. Even if it is
loaded, it will not be used but instead loads own version of JQuery.
The solution is to wrap the plugin code within a function definition. Once the plugin has
loaded, call that function, passing it the JQuery object as its only argument.
86
Advanced Java Script
Example:
/*Main page.html*/
<!doctype html>
<head>
<title> Loading JQuery plugins from third-party scripts – Example 1</title>
<meta charset=“utf-8”>
</head>
<body>
<h1>Loading JQuery plugins from third-party script</h1>
<h2> Example 1 </h2>
<p id=“hello”>Widget will write content here</p>
<script src= “widget.js”></script>
</body>
/*widget.js*/
(function(window, document) {“use strict”; /*Wrap code in an IIFE*/
Var JQuery, $;//Localize JQuery variables
Function loadScript(url, callback) {
/*Load script from url and calls callback once it’s loaded*/
Var scriptTag = document.createElement (‘script’);
scriptTag.setAttribute(“type”, “text/javascript”);
scriptTag.setAttribute(“src”, url);
if (typeof callback !== “undefined”) {
if (scriptTag.readyState) {
/*for old version of IE*/
ScriptTag.onreadystatechange = function() {
If (this.readyState === ‘complete’ || this.readyState=== ‘loaded’) {
Callback();
}
};
} else {
scriptTag.onload=callback;
}
}
(document.getElmentsByTagName(“head”)[0]||
87
Advanced Java Script
Document.documentElement).appendChild(scriptTag);
}
Function main() {
/* The main logic of our widget */
$(‘#hello’).html(‘This content comes from our widget’);
}
/*Load JQuery*/
loadScript(“…./jquery.js”, function() {
/* Restore $ and window.JQuery to their previous values and store the new JQuery in our local
JQuery variable.*/
$=JQuery=window.JQuery.noConflict(true);
Main(); /* Execute the main logic of our widget once JQuery is loaded*/
})
}(window, document)); /*end IIFE*/
/*plugin.js*/
Function initGreentifyPlugin(jQuery) {
(function ($) {
Var shade = “#556b2f”;
$.fn.greenify = function() {
This.css(“color”, shade);
Return this:
};
}(JQuery));
}
Updated widget code that calls plugin initializer and loads this plugins:
88
Advanced Java Script
Function main() {
/*The main ogic of our widget*/
$(‘#hello’).html(‘This content comes from our widget’).greenify();
}
/*Load JQuery*/
loadScript(“…/jquery.js”, function() {
/*restore $ and window.JQuery to their previous values and store the new JQuery in our local
JQuery variables.*/
$=JQuery= window.JQuery.noConflict(true);
/*Load JQuery plugin and execute the main logic of our widget once the plugin is loaded is loaded*/
loadScript(“…/modified-jquery-plugin.js”, function() {
initGreenifyPlugin(JQuery);
main();
});
});
JQuery Form Validation plugin is used to validate the form in the client side.
Types of validations:
1. Email Validation: Checks whether input field contains an email address.
2. NotEmpty Validation: Ensures that the field is not empty.
3. URL Validation: Ensures that the input is a valid url.
4. Regexp Validation: Ensures that a defined patterns is match character combinations in
string.
5. Length Validation: Checks whether input length is exact defined rules.
6. Min Length Validation: Ensures that input length should be greater than defined rules.
7. Phone Number Validation: Ensure that input is valid Mobile Number (Should be start
from 7 and exact 19 digit (This is for India Mobile Number))
8. Numeric Validation: Checks whether the field contains only numeric digits.
89
Advanced Java Script
2. Create a simple a form who has contain Name, Phone Number, Email, Website, Code, Filed
should be contain min length, Field should be contain only digits. We need to define Id of the
form. Let id id “myform”.
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<!--Latest compiled and minified BootStarp CSS -->
<link rel=“stylesheet”
href=“https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css”>
<!-- JQuery library-->
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js”> </script>
<!--JQuery Form Validation library-->
<script src=“https://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js”>
</script>
</head>
<body>
<div id=“page-wrapper”>
<div class=“container”>
<h1> Form Validation</h1>
<form name=“myForm” class=“form-horizontal” id=“myForm” action=“#” method=“POST”
enctype=“multipart/form-data”>
<div class= “panel panel-info”>
<div class= “panel-heading”>Form validation</div>
90
Advanced Java Script
91
Advanced Java Script
<div class=“form-group”>
<label for=“url” class=“col-md-4”> Website </label>
<div class=“col-md-6”>
<input type=“text” class=“form-control” name=“url” placeholder=“Enter Url”>
</div>
</div>
</div>
<!-- end div-->
</div>
<!-- end div-->
</div>
</div>
</div>
<div class=“col-md-4 col-md-offset-4” style= “margin-bottom:50px;”>
<center>
<input type=“submit” class=“btn btn-primary” value= “Submit”/>
</center>
</div>
</form>
</div>
</div>
</body>
</html>
Form Validation
92
Advanced Java Script
Display: inline-block;
Margin: 0px 0 0px 0px;
Padding: 0;
Text-align: left;
}
</style>
4. Finally add JQuery to define rules to validate input field. In the validation, we will define rules
for specific input field name.
93
Advanced Java Script
digits: true,
required: true,
minlength: 5
}
},
messages: {
name: “Please Enter Name”,
phone: “Please Enter Valid Mobile Number”,
email: “Please Enter valid Email”,
code: “please Enter 11 Digit code”,
min_length: “Please Enter Minimum 3 Digit”,
number: “Please Enter Only Digits”,
url: “Please Enter Websites Url”
},
submitHandler: function (form) {
form.submit();
}
});
}
}
//when the dom has loaded setup form validation rules
$(D).ready(function ($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(JQuery, window, document);
</script>
Form Validation
94
Advanced Java Script
3. Since JQuery pushes content to the client, it therefore reduces the wait time for server response.
4. JQuery makes animated applications just like Flash. It is smaller than Flash, so it results in
smoother playbacks and less errors.
5. Google and other search engines using page load time as one of the many factors affecting SEO.
JQuery pages load faster
6. It works anywhere. HTML5 is cross-browser compatible. So, it will work on any browser,
mobile phone or tablet, and even on Apple devices.
7. There’s a low learning curve. Since it’s based on plain old JavaScript, developers can learn
JQuery fast.
8. JQuery easily integrates with the Visual Studio IDE
Effect
Utilities
Effects Hide
Toggle Class
Toggle Toggle Remove Class
Toggle Show
Switch Class
95
Advanced Java Script
Q.3. List out the methods of JqueryUI plugin and describe them.
JqueryUI Interaction Methods:
The following table lists the JqueryUI Interaction Methods:
S.N JqueryUI Interactive plugin
Description
o Method
1 draggable() Allow elements to be moved using the mouse
2 droppable() Used to reate targets for draggable elements.
3 resizable() Used to change the size of an element using the mouse
4 selectable() Used to select elements, individually or in a group using
the mouse
5 sortable() Used to reorder elements in list or grid using the mouse.
96
Advanced Java Script
tooltip.
97
Advanced Java Script
JqueryUI Effect Methods: The following table lists the JqueryUI Effect methods:
S.N JqueryUI Effect plugin
Description
o Method
1 Color Animation Animate the properties of elements between colors.
2 Easing Apply an easing equation to an animation
3 Effect effect() method applies an animation effect to the elements
without having to show or hide it.
4 Hide effect() method applies an animation effect to hide elements.
5 Show show() method displays an item using the indicated effect.
6 Toggle Toggles the show() or hide() methods depending on whether the
element is hidden or not.
7 Toggle class adds or removes one or more classes from each element in the set
of matched elements.
8 Add class Add specified classes to the matched elements while animating all
style changes
9 Remove class Removes the specified classes to the matched elements while
animating all style changes.
10 Switch class Move from one CSS one CSS class to another, animating the
transition from one state to the other.
98
Advanced Java Script
99
Advanced Java Script
</head>
<body>
<div data-role=“page” id=“pageone” data-theme=“a”>
<div data-role= “header”> <h1> Vikas Publishers </h1> </div>
<div data-role= “main” class= “ui-content”>
<p> Text link</p>
<a href=“#” > A Standard Text Link</a>
<a href=“#” class=“ui-btn”> Link Button</a>
<p> A List View: </p>
<ul data-role=“listview” data-autodividers=“true” data-inset=“true”>
<li> <a href=“#” >Android </a> </li>
<li> <a href=“#” > IOS </a></li>
</ul>
Example:
<!DOCTYPE html>
<html>
<head>
<meta name=“viewport” content=“width=device-width, initial-scale=1”>
<link rel=“stylesheet” href= “https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css”>
<script src= “https://code.jquery.com/jquery-1.11.3.min.js”> </script>
<script src= “https://code.jquery.com/jquery-1.11.3.min.js”> </script>
<script src= “https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js”> </script>
</head>
<body>
100
Advanced Java Script
The JQuery UI Widget Factory is simply a function ($.widget) that takes a string name and an object
as arguments and creates a JQuery plugin and a “Class” to encapsulate its functionality.
Syntax
JQuery.widget(name [, base ], prototype)
Example:
Create : function() creates custom control, _setOption function is used to define an options
object which stores the default values for all of the options, Move method, that shifts the button a
specified horizontal distance. Firing an event when if the button moves beyond x=400
101
Advanced Java Script
<!DOCTYPE html>
<html>
<head>
<meta charset= “utf-8”>
<title> JQuery UI Widget – Default functionality </title>
<link rel=“stylesheet” href= “//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css”>
<script src= “https://code.jquery.com/jquery-1.10.2.js”> </script>
<script src= “https://code.jquery.com/ui/1.10.4/jquery-ui.js”> </script>
<script>
$(function() {
$.widget(“P.myButton”, {
_create: function() {
this_button=$(“<button>”);
this_button.text(“My first Widget Button”);
this_button.width(this.options.width)
this_button.css(“background-color”, this.option.color);
this_button.css(“position”, “absolute”);
this_button.css(“left”, “100px”);
$(this.element).append(this_button);
},
move: function(dx) {
var x=dx + parselnt(this.__button.css(“left”));
this._buton.css(“left”, x);
If(x>400) {this._trigger(“outbounds”, {}, {position:x});}
}
});
$(“#button4”).myButton();
$(“#button4”).on(“mybuttonoutbounds”, function(e, ui) {
alert(“out”);
});
$(“#button4”).myButton(“move”, 500);
});
</script>
</head>
<body>
<div id= “button4”> </div>
</body>
</html>
102
Advanced Java Script
UNIT – IV
INTRO TO AJAX
Essay Questions
Q.1. Explain how to insert, delete, and update data into database using jquery-ajax.
Insert data into database using jquery-ajax with PHP: To insert data into a database, a
connection must be obtained with the database. The following function establishes a connection
with the database.
103
Advanced Java Script
Once the connection is established, data can be updated into the database. The following function
can be used to update the given data into a database.
foreach($data as $key=>$val) {
$pre=($i>0)?’, ‘:”;
$colvalSet .=$pre.$key.“=“‘.$val.” ”’;
$i++;
}
If(!empty($conditions)&& is_array($conditions)){
$whereSql .=‘WHERE’;
104
Advanced Java Script
$i=0;
foreach($conditions as $key=>$value) {
$pre=($i>0)?‘AND’:”;
$whereSql .=$pre.$key.“= ‘“.$value.” ”’;
$i++;
}
}
$query=“UPDATE”.$table. “SET”.$colvalSet.$whereSql;
$update= $this->db->query($query);
return $update?$this->db->affected_rows:false;
}else{
return false;
}
}
Once the connection is established, data can be deleted from the database. The following function
can be used to delete the specified data from a database.
105
Advanced Java Script
$i++;
}
}
$query=“DELETE FROM”.$table.$whereSql;
$delete= $this->db->query($query);
return $delete?true:false;
}
Example:
STEP 1
<div>
<input id=“clientworkers” type=“button” value=“Get Client Workers Data”
onclick=“clientworkersdatabind()”/>
<asp:Button Text=“Get Server Workers Data” runat=“server” ID=“Serverworkers”OnClientClick=
“javascript:return serverworkersdatabind()”/>
<br/>
<br/>
<table id= “Workerstable”>
<thead>
<tr>
<th> Employee Name</th>
<th> Post</th>
<th> Age </th>
<th> Working in</th>
<th>DataSource</th>
</tr>
</thead>
</table>
</div>
STEP 2:
<script id=“workersTemplate” type= “text/html”>
<tr>
<td>$(EmployeeName)</td>
106
Advanced Java Script
<td>${Post}</td>
<td>{{if Age>30}}
<span style=‘background-color:red’> Middle-aged</span>
{{else}}
<span style=‘background-color:yellow’>Still young</span>
{{/if}}</td>
<td>${Workingin}</td>
<td>${DataSource}</td>
</tr>
</script>
STEP 3:
To add the data to the client side add the following code to the .aspx page:
<script type= “text/javascript”>
function clientworkersdatabind(){
var workers= [
{EmployeeName: “Anubhav”, Post: “Developer”, Age: 24, Workingin: “IT”, DataSource: “Client”},
{EmployeeName: “Ashwini”, Post: “Trainee”, Age: 24, Workingin: “IT”, DataSource: “Client”},
{EmployeeName: “Dinesh”, Post: “Senior Manager”, Age: 35, Workingin: “HR”, DataSource: “Client”},
{EmployeeName: “Swati”, Post: “Tester”, Age: 27, Workingin: “Testing”, DataSource: “Client”},
{EmployeeName: “Hari”, Post: “Trainer”, Age: 40, Workingin: “IT”, DataSource: “Client”},
]
BindTable(workers);
}
To add the data to the server side go to the aspx.cs page and add this code:
Public static object ServerWorkers()
{
List<object> workers=new List<object>();
Worker.Add(new{EmployeeName=“Anubhav”, Post=“Developer”, Age:=45, Workingin=“IT”,
DataSource=“Server”});
Worker.Add(new{EmployeeName=“Ashwini”, Post=“Trainee”, Age=38, Workingin=“IT”,
DataSource=“Server”});
Worker.Add(new{EmployeeName=“Dinesh”, Post=“Senior Manager”, Age=20, Workingin=“HR”,
DataSource=“Server”});
Worker.Add(new{EmployeeName=“Swati”, Post=“Tester”, Age=27, Workingin=“Testing”,
DataSource=“Server”});
Worker.Add(new{EmployeeName=“Hari”, Post=“Trainer”, Age=25, Workingin: “IT”,
DataSource=“Server”});
107
Advanced Java Script
Return workers;
STEP 4:
function serverworkersdatabind() {
$.ajax({
type: “POST”,
url: “JQueryGridTemplate.aspx/ServerWorkers”,
data: “{}”,
contentType: “application/json; charset=utf-8”,
dataType: “json”,
success:function(msg, status, metaData) {
if(msg.d && msg.d.length>0) {
BindTable(msg.d);
}
},
error:function(ex, status) {
Alert(“error”);
},
complete:function(eret, tyty) {
}
});
Return false;
}
108
Advanced Java Script
Accessing JSON objects: the object values can be accessed by using dot(.) notation:
<!DOCTYPE html>
<html>
<body>
<p>Access a JSON object using dot notation:</p>
<p id=“demo”></p>
<script>
var myObj, x;
myObj={“name”:“John”, “age”:30, “car”:null};
x=myObj.name;
document.getElementByld(“demo”).innerHTML=x;
</script>
</body>
</html>
The object values can also be accessed by using bracket ([]) notation:
<!DOCTYPE html>
<html>
<body>
<p>Access a JSON object using bracket notation:</p>
<p id=“demo”></p>
<script>
var myObj, x;
myObj={“name”:“John”, “age”:30, “car”:null};
x=myObj[“name”];
document.getElementByld(“demo”).innerHTML=x;
</script>
</body>
</html>
Looping an Object: Looping is done through object properties by using the for-in loop:
myObj={“name”:“John”, “age”:30, “car”:null};
for(x in myObj){
document.getElementByld(“demo”).innerHTML +=x;
}
In a for-in loop, the bracket notation is used to access the property values:
myObj={“name”:“John”, “age”:30, “car”:null};
for(x in myObj){
document.getElementByld(“demo”).innerHTML +=myObj[x];
}
109
Advanced Java Script
Nested JSON Objects (Complex JSON objects): Values in a JSON object can be nested into another
JSON object. These objects and arrays will be passed as values assigned to keys, and typically will be
comprised of key-value pairs as well.
myObj={
“name”: “John”,
“age”:30,
“cars”:{
“car1”: “Ford”,
“car2”: “BMW”,
“car3”: “Fiat”
}
}
Curly braces are used throughout to form a nested JSON object and just like any other value, when
using objects, commas are used to separate elements.
Nested JSON objects can be accessed by using the dot notation or bracket notation:
x=myObj.cars.car2;
//or:
x=myObj.cars[“car2”];
Modify Values: the dot notation can be used to modify any value in a JSON object:
myObj.cars.car2= “Mercedes”;
The bracket notation can also be used to modify a value in a JSON object:
myObj.cars[“car2”]= “Mercedes”;
Delete Object Properties: Use the delete keyword to delete properties from a JSON object:
delete myObj.cars.car2;
110
Advanced Java Script
refresh. Ajax can be defined as “the method of exchanging data with a server, and updating parts of
a web pages – without reloading the entire page.”
Ajax itself is mostly a generic term for various JavaScript techniques used to connect to a web
server dynamically without necessarily loading multiple pages. In a more narrowly –defined sense,
it refers to the use of XmlHttpRequest objects to interact with a web server dynamically via
JavaScript.
Benefits of Ajax: There are four main benefits of using Ajax in web applications:
1. Callbacks: Ajax is used to perform a callback, making a quick round trip to and from the server
to retrieve and/or save data without posting the entire page back to the server. By not
performing a full postback and sending all form data to the server, network utilization is
minimized and quicker operations occur. In sites and locations with restricted bandwidth, this
can greatly improve network performance. Most of the time, the data being sent to and from the
server is minimal. By using callbacks, the server is not required to process all form elements. By
sending only the necessary data, there is limited processing on the server. There is no need to
process all form elements, process the ViewState, send images back to the client, or send a full
page to the client.
2. Making Asynchronous Calls: Ajax allows you to make asynchronous calls to a web server. This
allows the client browser to avoid waiting for all data to arrive before allowing the user to act
once more.
3. User-Friendly: Because a page postback is being eliminated, Ajax enabled applications will
always be more responsive, faster and more user-friendly.
4. Increased Speed: The main purpose of Ajax is to improve the speed, performance and usability
of a web application. A great example of Ajax is the movie rating feature on Netflix. The user
rates a movie and their personal rating for that movie will be saved to their database without
waiting for the page to refresh or reload. These movie ratings are being saved to their database
without posting the entire page back to the server.
111
Advanced Java Script
$(“#responsecontainer”).html(response);
}
});
});
});
</script>
<body>
<h3 align=“center”>Manage Student Details</h3>
<table border=“1” align=“center”>
<tr>
<td><input type=“button” id=“display” value=“Display All Data”/> </td>
</tr>
</table>
<div id=“responsecontainer” align=“center”> </div>
</body>
</html>
(2) PHP file to connect database and retrieve data from Database:
<?php
$con=mysqli_connect(“localhost”, “root”, “”);
If(!$con)
{
die(‘Could not connect: ‘. mysqli_error());
}
mysqli_select_db(“samples”, $con);
$result=mysqli_query(“select *from student”, $con);
echo “<table border= ‘1’>
<tr>
<td align=center> <b> Roll No </b></td>
<td align=center> <b> Name </b></td>
<td align=center> <b> Address </b></td>
<td align=center> <b>Stream</b></td>
<td align=center> <b>Status</b></td>”;
while ($data=mysqli_fetch_row($result))
{
echo “<tr>”;
echo “<td align=center>$data[0]</td>”;
echo “<td align=center>$data[1]</td>”;
echo “<td align=center>$data[2]</td>”;
echo “<td align=center>$data[3]</td>”;
112
Advanced Java Script
JSON Values:
In JSON, values must be one of the following data types:
(a) a string
(b) a number
(c) an object(JSON object)
(d) an array
(e) a boolean
(f) null
In JavaScript values can be all of the above, plus any other valid JavaScript expression, including:
(a) a function
(b) a date
(c) undefined
113
Advanced Java Script
114
Advanced Java Script
$(document).ready(function(){
var jsonp=‘[{ “Lang”:“JQuery”, “ID”:“1”}, { “Lange”: “C#”, “ID”: “2”}]’;
var lang= “;
var obj=$.parseJSON(jsonp);
$.each(obj, function() {
Lang+=this[‘Lang’] + “<br/>”;
});
$(‘span’).html(lang);
});_
Accessing Array Values: The array values can be accessed by using the index number:
x=myObj.cars[0];
Looping Through an Array: array values can be accessed by using a for-in loop:
for (i=0; i<myObj.cars.length; i++){
x += myObj.cars[i];
}
Nested Arrays in JSON Objects: Values in an array can also be another array, or even another JSON
object:
myObj={
“name”: “John”,
115
Advanced Java Script
“age”:30,
“cars”:[
{“name”:“Ford”, “models”:[“Fiesta”, “Focus”, “Mustang”]},
{“name”:“BMW”, “models”:[“320”, “X3”, “X5”]},
{“name”:“Fiat”, “models”:[“500”, “Panda”]}
]
}
To access arrays inside arrays, for-in loop is used for each array:
for (i in myObj.cars) {
x+=“<h1>”+myObj.cars[i].name+ “</h1>”;
for (j in myObj.cars[i].models) {
x+= myObj.cars[i].models[j];
}
}
Delete Array Items: The delete keyword is used to delete items from an array:
delete myObj.cars[1];
Q.6. List out the JQuery Ajax method and describe them.
jQuery Ajax Methods:
S.N
Methods Description
o
1 jQuery.ajax(options) Load a remote page using an HTTP request.
2 jQuery.ajaxSetup(options) Setup global settings for AJAX requests.
3 jQuery.get(url, [data], [callback], Load a remote page using an HTTP GET request.
[type])
4 jQuery.getSON(url, [data], Load JSON data using an HTTP GET request.
[callback])
5 jQuery.getScript (url, [callback]) Load and executes a JavaScript file using an HTTP GET
request.
6 jQuery.post(url, [data], [callback], Load a remote page using an HTTP POST request.
[type])
7 load(url, [data], [callback]) Load HTML from a remote file and inject it into the
DOM.
8 serialize() Serializes a set of input elements into a string of data.
9 serializeArray() Serializes all forms and form elements like the
.serialize() method but returns a JSON data.
116
Advanced Java Script
UNIT – V
INTRO TO ANGULAR JS
Essay Questions
Open the link https://angularjs.org/ there are two options to download AngularJS library:
1. View on GitHub – Click on this button to go to GitHub and get all of the latest scripts.
2. Download AngularJS 1 – Or click on this button, a screen as below would be seen:
Download AngularJS
117
Advanced Java Script
1.There are two different options legacy and latest. The names itself are self-
descriptive. Legacy has version less than 1.2.x and latest has 1.5.x version.
2.We can also go with the minified, uncompressed or zipped version.
ii. CDN access: You also have access to a CDN. The CDN will give you access around the
world to regional data centers that in this case, Google host. This means using CDN
moves the responsibility of hosting files from your own servers to a series of
external ones. This also offers an advantage that if the visitor to your webpage has
already downloaded a copy of AngularJS from the same CDN, it won’t have to be re-
downloaded.
iii. Try the new AngularJS 2: Click on this button to download AngularJS beta 2
version. This version is very fast, mobile supported and flexible compare to legacy
and latest of AngularJS 1.
On removing the ng-app directive, HTML will display the expression as it is, without solving it:
<!DOCTYPE html>
<html>
<script src= “https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js”> </script>
<body>
<div>
<p>My first expression:{{5+5}}</p>
</div>
</body>
</html>
118
Advanced Java Script
AngularJS change the value of CSS properties. The color of the input box can be changed by
changing its value:
<div ng-app=“” ng-init=“myCol= ‘lightblue’”>
<input style= “background-color:{{myCol}}” ng-model= “myCol” value= “{{myCol}}”>
</div>
AngularJS Numbers:
AngularJS numbers are like JavaScript numbers:
<div ng-app=“” ng-init=“quantity=1; cost=5”>
<p>Total in dollar:{{quantity*cost}}</p>
</div>
119
Advanced Java Script
120
Advanced Java Script
The “myApp” parameter refers to an HTML element in which the application will run.
Controllers, directives, filters can be added to the module created.
Controller Module:
studentController.js
mainApp.controller(“studentController”,function($scope) {
$scope.student={
firstName: “Technical”,
lastName: “Publishers”,
fees:500,
subjects:[
{name: ‘Physics’, marks:70},
{name: ‘Chemistry’, marks:80},
{name: ‘Math’, marks:65},
{name: ‘English’, marks:75},
{name: ‘Hindi’, marks:67},
],
fullName:function() {
var studentObject;
studentObject=$scope.student;
return studentObject.firstName + “ ” + studentObject.lastName;
}
};
});
121
Advanced Java Script
Application module is used by using ng-app directive and controller by using ng-controller
directive.
Example:
<html>
<head>
<title>AngularJS Modules</title>
<script src=“https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js”> </script>
<script src= “/angularjs/src/module/mainApp.js”> </script>
<script src= “/angularjs/src/module/studentController.js”> </script>
<style>
table, th, td {
border:1px solid grey;
border-collapse:collapse;
padding:5px;
}
table tr:nth-child(odd){
background-color:#f2f2f2;
}
table tr:nth-child(even){
background-color:#ffffff;
}
</style>
</head>
<body>
<h2> AngularJS Sample Application</h2>
<div ng-app= “mainApp” ng-controller=“studentController”>
<table border= “0”>
<tr>
<td>Enter first name:</td>
<td> <input type= “text” ng-model= “student.firstName”></td>
</tr>
<tr>
<td>Enter last name:</td>
<td> <input type= “text” ng-model= “student.lastName”></td>
</tr>
<tr>
<td>Name:</td>
122
Advanced Java Script
<td>{{student.fullName()}}</td>
</tr>
<tr>
<td>Subject:</td>
<td>
<table>
<tr>
<th>Name</th>
<th>Marks</th>
</tr>
<tr ng-repeat= “subject in student.subjects”>
<td>{{subject.name}}</td>
<td>{{subject.marks}}</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</body>
</html>
123
Advanced Java Script
var studentObject;
studentObject=$scop.student;
return studentObject.firstName +“ ” + studentObject.lastName;
}
};
}
</script>
<body>
<h2> AngularJS Sample Application</h2>
<div ng-app=“mainApp” ng-controller=“studentController”>
Enter first name: <input type=“text” ng-model=“student.firstName”> <br> <br>
124
Advanced Java Script
(a) $scope is passed as first argument to controller during its constructor definition.
(b) $scope.message and $scope.type are the models which are to be used in the HTML page.
(c) We have set values to models which will be reflected in the application module whose
controller is shapeController.
(d) We can define functions as well in $scope.
Scope Inheritance: Scope are controllers specific. If we define nested controllers then child
controller will inherit the scope of its parent controller.
<script>
var mainApp=angular.module(“mainApp”,[]);
mainApp.controller(“shapeController”, function($scope){
125
Advanced Java Script
126
Advanced Java Script
$scope.type=“Square”;
});
</script>
</body>
</html>
$scope.square=function() {
$scope.result=CalcService.square($scope.number);
}
});
2. Factory: Factory is a function which is used to return value. It creates value on demand
whenever a service or controller requires. It normally uses a factory function to
calculate and return the value.
//define a module
127
Advanced Java Script
var mainApp=angular.module(“mainApp”,[]);
//create a factory “MathService” which provides a method multiply to return multiplication of two
numbers
mainApp.factory(‘MathService’, function() {
var factory={};
factory.multiply=function(a, b) {
return a*b
}
return factory;
});
//inject the factory “MathService” in a service to utilize the multiply method of factory.
mainApp.service(‘CalcService’, function(MathService){
this.square=function(a){
return MathServce.multiply(a,a);
}
});
…..
3. Service: Service is a singleton javascript object containing a set of functions to perform certain
tasks. Services are defined using service() functions and then injected into controllers.
//define a module
var mainApp=angular.module(“mainApp”,[]);
…
{
$scope.number=defaultInput;
$scope.result=CalcService.square($scope.number);
$scope.square=function(){
$scope.result=CalcService.square($scope.number);
}
});
128
Advanced Java Script
4. Provider: Provider is used by AngularJS internally to create services, factory etc. during config
phase (phase during which AngularJS bootstraps itself). Below mention script can be
used to create MathService that we’ve created earlier. Provider is a special factory
method with a method get() which is used to return the value/service/factory.
//define a module
var mainApp=angular.module(“mainApp”,[]);
…
//create a service using provider which defines a method square to return square of a number.
mainApp.config(function($provide) {
$provide.provider(“MathService’, function() {
this.$get=function(){
var factory={};
factory.multiply=function(a,b){
return a*b;
}
return factory;
};
});
});
(5) Constant: Constants are used to pass values at config phase considering the fact that value can
not be used to be passed during config phase.
mainApp.constant(“configParam”, “constant value”);
example
<html>
<head>
</head>
<body>
<p> Result:{{result}}</p>
129
Advanced Java Script
</div>
130