Biology for Computer Engineers Course Handout.pptx
Unit – II (1).pptx
1. Unit – II
Building Interactive Web Pages with
jQuery:Building Interactive Web Pages with
jQuery:
2. Contents
Dynamically Accessing and Manipulating Web Pages with JavaScript and
jQuery – Working with Window, Browser, and Other Non-Web Page Elements
– Enhancing User Interaction Through jQuery Animation and Other Special
Effects – Interacting with Web Forms in jQuery and JavaScript – Creating
Advanced Web Page Elements in jQuery.
3. Dynamically Accessing and Manipulating Web Pages with JavaScript
and jQuery
1. Accessing Browser and Page Element Values
2. Dynamically Manipulating Page Elements
3. Dynamically Rearranging Elements on the Web Page
4. 1.Accessing Browser and Page Element Values
Getting Mouse Position
The mouse position is accessible from the event object when a mouse event is
triggered
6. Getting and Setting Values
jQuery provides the .val() method to retrieve and set the value
Getting and Setting Attributes and Properties in jQuery
● jQuery provides the .attr() and .prop() methods to get and set the attributes and
properties of these elements.
● The .attr(attribute, [value]) method allows you to specify an attribute name only to
get the current value, as well as an optional value to set the current value.
● The .prop(property, [value]) method allows you to specify the property to get the
current value and an optional value to set the current value.
7. ● Difference: As of jQuery 1.6, the .prop() method provides a way to explicitly
retrieve property values, while .attr() retrieves attributes.
○ For example, selectedIndex, tagName, nodeName, nodeType,
ownerDocument, defaultChecked, and defaultSelected should be
retrieved and set with the .prop() method.
○ Prior to jQuery 1.6, these properties were retrievable with the .attr()
method, but this was not within the scope of attr. These do not have
corresponding attributes and are only properties.
10. Getting and Setting CSS Properties
● jQuery provides css(property, [value]) method to get and set CSS values
● The .css() method is used to pass a map object with properties and values
● The .css() method is also used to set the margin, padding, float, and font-
weight attributes at the same time
13. Example: (innerHeight() and innerWidth())
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#p1").text($("div").innerWidth());
$("#p2").text($("div").innerHeight());
});
});
</script></head><body>
<div style="height:100px;width:300px;padding:10px;margin:3px;
border:1px solid blue;background-color:lightblue;"></div><br>
<p id="p1"></p>
<p id="p2"></p>
<button>Display the innerheight and innerwidth of div</button>
</body>
</html>
14. Getting and Setting Element Position
● jQuery provides the .position([position]) method to get the position relative to the
offset parent.
● The .offset([position]) method provides the position relative to the document.
● Both of these methods can be called with no argument.
● They return a simple object with a left and right attribute that represent the
number of pixels from the left and top of document when using .position() or
offset parent when using .offset().
15. Example: (innerHeight() and innerWidth())
<html><head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var x = $("p").offset();
alert("Top: " + x.top + " Left: " + x.left);
var z = $("p").position();
alert("Top: " + z.top + " Left: " + z.left);
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button>click to display the offset and position</button>
</body>
</html>
16. Accessing the Class
● The simplest way to get the classes associated with an HTML element is to look at
the className attribute of the DOM object.
● The className attribute is a string containing the names of the class(es)
attached to the element.
Getting Browser and Screen Size and Color Information
● The Screen object provides the width and height attributes that are the screen
resolution dimensions
● The colorDepth attribute of the Screen object is used to get the supported
colors by the screen .This returns a value of the number of bits supported
● The browser dimensions can be accessed from the innerWidth, outerWidth,
innerHeight, and outerHeight attributes of the window object available in
JavaScript.
17. Example: (attr() to get class name)
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var className = $("p").attr("class");
alert(className);
});
});
</script>
</head>
<body>
<p class="p1">This is a paragraph.</p>
<button>click</button>
</body>
</html>
19. 2.Dynamically Manipulating Page Elements
1.Adding Page Elements Dynamically(Adding Page Elements in JavaScript)
● There are several ways to add HTML elements dynamically.
● The most basic is to set the innerHTML attribute of a container object
to an HTML string.
20. Example:
<html>
<body>
<h1>Adding page dynamically</h1>
<p id="p1">paragraph 1.</p>
<p id="p2"></p>
<script>
document.getElementById("p2").innerHTML = "paragraph 2";
var para = document.createElement("p");
var node = document.createTextNode("This is new para.");
para.appendChild(node);
var element = document.getElementById("p2");
element.appendChild(para);
</script>
</body>
</html>
21. Adding Page Elements in jQuery
● The html() method sets or returns the content (innerHTML) of the selected elements.
<html><head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var newP = $("<p></p>");
newP.html("Paragraph 2");
$("p").append(newP);
});
});
</script></head>
<body>
<h1> Adding page dynamically </h1>
<p> Paragraph 1 </p>
<button>click to set p</button>
</body></html>
22. 2.Removing Page Elements(javascript)- removeChild() method removes an element's child.
<html><head>
<script type="text/javascript">
function myFunction()
{
var list = document.getElementById("myList");
list.removeChild(list.childNodes[0]);
}
</script>
</head>
<body>
<ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>
<p>Click the button to remove the first item in the the list.</p>
<input type="submit" value="replace" onclick="myFunction()">
</body>
</html>
23. Removing Page Elements(jQuery)- remove() method removes the
selected elements
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#p1").remove();
});
});
</script>
</head>
<body>
<p id="p1">This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Remove first p elements</button>
</body></html>
24. 3.Replacing Elements in jQuery
● The .html() method in jQuery is extremely useful for replacing the contents
of an existing element with completely different content.
● Another method of replacing a set of elements in the document with new
content is the .replaceAll(target) method. This method replaces the set of
elements that match the target selector with those of the current set.
● The final method is to use .replaceWith(newContent), which does the
opposite of .replaceAll(). The .replaceWith() function replaces the elements
in the current set with the content specified.
26. 4.Inserting Elements in jQuery-The .after() and .before() methods
are used to to pass in multiple objects to insert, separated by a comma.
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p:eq(1)").after($("<p>after Paragraph</p>"));
$("p:eq(1)").before($("<p>before Paragraph</p>"));
});
});
</script>
</head>
<body>
<p>para 1</p>
<p>para 2</p>
<button>click</button>
</body>
</html>
27. 5.Changing Classes-
● The addClass() and removeClass methods are used to change the classes of
the html element
● .toggleClass(className [, switch) method. In addition to the className, you
can specify a true or false for the optional switch parameter indicating to
turn the class on or off.
○ Example -$("span").toggleClass("active", true);
$("span").toggleClass("inactive", false);
29. 6.Toggling Visibility
● To display an element using jQuery, call the .show() method on that object. Then
to hide the element, use the .hide() method.
● Example
○ jObj.hide();
○ jObj.show();
● To make an element invisible, set the opacity CSS property to 0.
For example:
jObj.css("opacity", "0");
● To make the element visible again, set the opacity back to 1:
jObj.css("opacity", "1");
31. 3.Dynamically Rearranging Elements on the Web Page
Adjusting the z-index
● The z-index is a CSS property that specifies the position of an HTML
element with respect to other elements
● The z-index specifies the order of stack for an element. The element
which has the highest order of stack always appear in front of the
element which have the lowest order of stack
34. Working with Window, Browser, and Other Non-Web Page
Elements
1. Understanding the Screen Object
2. Using the Window Object
3. Using the Browser Location Object
4. Using the Browser History Object
5. Controlling External Links
6. Adding Pop-up Boxes
7. Setting Timers
37. 2.Using the Window Object
The window object provides access to the browser window and it is used to
get information such as the dimensions and position of the browser window.
Accessing the Window Object Properties
40. Using the Window Object Methods
● The window object also provides a set of methods that allow you to
create and manage additional child windows from your JavaScript code.
Window Object Methods
44. 3.Using the Browser Location Object
Using the Browser Location Object
● The browser location object is used to access the current location in the
browser.
● It is also used to access all the URL information as well as reload the
current page or load a new one in the current window.
47. 4.Using the Browser History Object
● The history object provides access to the browser navigation history, and
it is used to move forward and backward dynamically without the user
needing to click the browser Forward and Back buttons
● Navigating Forward in the Browser History
○ The history.forward() is used to move to the next URL in the history
○ history.go(n) is also used, where n is a positive number that represents the number of
steps to move forward.
● Navigating Backward in the Browser History
○ history.back() is used to move to the previous URL in the history,
○ history.go(n) is also used , where n is a negative number that represents the number of
steps to move backward.
50. <body>
<h1>The Window History Object</h1>
<h2>Page 2</h2>
<button id="b1">forward</button>
<button id="b2">back</button>
</body></html>
Output for forward click
Output for back click
51. 5.Controlling External Links
● An important part of dynamic web programming also involves controlling
the linkage outside of the web page.
Stopping External Links on a Web Page
● To lock down external links from a web page, click event handler is added
to the <a> tags that link externally and then call preventDefault() on the
click event object.
● The preventDefault() method is used to prevent the browser from
executing the default action of the selected element.
Forcing Links to Open in New Browser Windows
● To force external links to open in a new window, set the target attribute
to “_blank” for <a> tags that link externally
53. Example:
<html>
<body>
<h1>The a target attribute</h1>
<p>Open link in a new window or tab:
<a href="https://www.w3schools.com" target="_blank">Visit W3Schools!</a>
</p>
</body>
</html>
54. 6.Adding Pop-up Boxes
Notifying the User
● The most common type of pop-up is an alert pop-up designed to notify the
user that something has happened.
● window.alert() method is used to create a simple alert message
Asking the User to Confirm
● The next most common type of pop-up is a confirmation pop-up designed to
notify the user that something is about to happen
● window.confirm() method is used to create a confirmation dialog box that
allows the user to respond with yes or no
Prompting the User for Input
● The prompt displays a text box that allows the user to type a text string into
the pop-up box
● window.prompt() method is used to create a prompt dialog that allows the
user to input a single text string as input
57. 7.Setting Timers
● Another useful feature of JavaScript is the capability to set timers that
execute a function or evaluate an expression after a certain amount of
time or on a specific interval.
Adding a Delay Timer
● To delay the execution of code for a certain amount of time, use the
setTimeout(code, ms) method, where code is either a statement or a
function that will execute when the time expires. ms is the number of
milliseconds.
Adding a Reoccurring Timer
● The setInterval(code, ms) method accepts a code statement or a
function name and milliseconds as arguments.
59. Enhancing User Interaction Through jQuery Animation and Other
Special Effects
1. Understanding jQuery Animation
2. Animating Show and Hide
3. Animating Visibility
4. Sliding Elements
5. Creating Resize Animations
6. Implementing Moving Elements
60. 1.Understanding jQuery Animation
● jQuery animation is the process of modifying a property of an HTML element
from one value to another in an incremental fashion visible to the user
Animating CSS Settings
● The .animate() jQuery method is used to implement animations on one or more CSS
properties.
Animating options
● complete
● duration
● easing(linear,swing(bydefault))
● queue
● step
● specialEasing
64. Understanding Animation Queues
● By default, jQuery comes with queue functionality for animations.
● jQuery creates an "internal" queue with multiple ‘animate’ method calls. it runs the animate
calls ONE by ONE.
Stopping Animation
● The jQuery stop() method is used to stop an animation or effect before it is finished.
● $("img").stop(true);
○ stops all animations on images and removes the animations from the queue
● $("img").stop(true, true);
○ Calling .stop(true, true), with the jumpToEnd option set to true, causes the currently
executing animation to jump to the end value immediately, clear the queue, and then stop
all animations
67. Delaying Animation
● A great option when implementing animations is adding a delay before the
animation is added to the queue
● .delay(duration, [, queueName])
Applying .promise() to Animations
● This .promise() method in JQuery Returns a Promise object to be observed
when certain type actions bounded to the collection, queued or not, are
ended.
● .promise([type], [, target])
70. 2.Animating Show and Hide
Animating hide()
● The .hide( [duration] [, easing] [, callback]) method provides the optional duration,
easing, and callback options that help to animate the hide effect, making less of a
jump when the element disappears.
Animating show()
● The .show( [duration] [, easing] [, callback]) method provides the optional duration,
easing, and callback options that help to animate the show effect, making a more
easy transition as an element appears.
Animating toggle()
● The .toggle( [duration] [, easing] [, callback]) method provides the optional
duration, easing, and callback options that help to animate the toggle between the
show or hide effect when toggling between them.
72. 3.Animating Visibility
fadeIn()
● The .fadeIn( [duration] [, easing] [, callback]) method provides the optional duration,
easing, and callback that help to animate fading the opacity of an element from its current
value to 1.
fadeOut()
● The .fadeIn( [duration] [, easing] [, callback]) method provides the optional duration,
easing, and callback that help to animate fading the opacity of an element from its current
value to 0.
fadeToggle()
● The .fadeToggle( [duration] [, easing] [, callback]) method provides the optional duration,
easing, and callback options allowing you to animate fading the opacity of an element from
its current value to 0 or 1, depending on its current value.
fadeTo()
● The .fadeTo( duration, opacity [, easing] [, callback]) method provides the duration and
opacity options that specify a specific opacity to end at and how long to animate the
transition.
74. 4.Sliding Elements
Animating slideUp(), slideDown(), and slideToggle()
● The .slideUp( duration [, easing] [, callback]), .slideDown( duration [, easing] [,
callback]), and .slideToggle( duration [, easing] [, callback]) methods provide the
duration, easing, and callback arguments that help to animate sliding effects in the
vertical direction.
Sliding Using Width and Height
● The width and height properties are used to create a sliding element.
● Example:
○ $("img").animate({height:100}, 1000);
76. 5.Creating Resize Animations
● The width and height properties are used to create a resize animation.
<html><head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#b1").animate({height:200,width:200},1000);
});
});
</script></head>
<body>
<button>Animate height</button>
<div id="b1" style="background:orange;height:100px;width:100px"></div>
</body></html>
77. 6.Implementing Moving Elements
Animating Element Position Changes on Static Elements
● By default, all HTML elements have a static position, and cannot be moved.
● However, you can animate the margin and padding properties.
Animating Element Position Changes on Nonstatic Elements
● if it is a fixed, absolute, or relative positioned element
○ Animate the elements with two values top and left.
○ top⇒To animate movement vertically
○ left⇒to animate horizontally
80. Interacting with Web Forms in jQuery and JavaScript
1. Accessing Form Elements
2. Intelligent Form Flow Control
3. Dynamically Controlling Form Element Appearance and Behavior
4. Validating a Form
81. 1.Accessing Form Elements
Getting and Setting Form Element Values
● Accessing Form Element Attributes
○ id—Used to query for and identify the form element.
○ name—Used in multiple fashions
○ type—Used to identify the type of <input> element.
○ value—Stores a value that is associated with the element
○ checked—Used to access the selection state of a radio or check box
● In jQuery, there are three ways to get the properties and attributes of the form objects:
the .attr(), .prop(), and .val() methods.
● The .attr() method is used to access attributes of the DOM object , whereas the .prop()
method is used to access properties of the DOM object
● jQuery provides the .val() method to access values represented by the form element
82. ● Accessing Text Input Elements
○ In jQuery, the value can be accessed using the .val() method of the jQuery object.
● Accessing Check Box Inputs
○ Check box input elements have a Boolean value based on whether the element is
checked.
○ The value is accessed by getting the value of the checked attribute.
○ jQuery object represents an object that is checked is the .is() method. For
■ Example:
● jObj.is(":checked");
○ To set the state of a jQuery object representing check boxes to checked, you set
the checked attribute as follows:
● jObj.prop("checked", true);
85. ● Accessing Radio Inputs
○ The radio inputs are almost always used in groups.
○ The value of a radio input group represents is not Boolean. Instead, it is the
value attribute of the currently selected element.
○ var groupValue = $("input[name=myGroup]").filter(":checked").val();
● Accessing Select Inputs
○ Select inputs are really container inputs for a series of <option> elements. The
value of the select element is the value(s) of the currently selected option(s).
○ To get that value is very simple in jQuery using the .val() method.
● Accessing Button Inputs
○ For the most part, you will not need to access button data, with the possible
exception of the value attribute, which defines the text displayed on the
button.
88. ● Accessing File Inputs
○ the HTML <input type=”file”> is used to select the file After that jQuery
change() method is used to get the file name. This method is used in the
JQuery to get the file input by selected file name.
● Properties of file object
91. ● Accessing Hidden Inputs
○ The hidden field is not shown to the user, but the data is sent when the form is
submitted.
○ The parts that will be sent with the form are the name and value attributes.
○ However, the additional values can be attached to a hidden form object, or any
HTML DOM object from jQuery, using the
■ .data(key[,value]) method.
94. ● Serializing Form Data
○ Many of the input elements in a form can be easily serialized into strings or
arrays.
○ Serializing the form data makes it easier to deal with when storing it, sending it
to a server, or dynamically making adjustments based on a form event.
○ For a form to be serialized, it needs two things:
■ a name attribute and
■ a value attribute that can be assigned to the name.
95.
96. ● Converting a Form into a Query String
○ One of the most common serialization tasks is converting the form data into a
serialized array.
○ jQuery makes this a snap with the .serialize() method.
○ The .serialize() method will access the form and convert the name/value pairs
into an URL-encoded string ready to be transmitted across the web.
99. ● Converting a Form into a JavaScript Object
○ Another very useful serialization technique is to convert the form data into a
JavaScript object that can then be accessed.
○ The jQuery .serializeArray() method is used to convert form into objects.
○ The serializeArray() method creates an array of objects (name and value) by
serializing form values
■ var formArr = $("#simpleForm").serializeArray();
101. <body>
<form action="">
First name: <input type="text" name="FirstName"><br>
Last name: <input type="text" name="LastName"><br>
</form>
<button>Serialize form values</button>
<div id="results"></div>
</body>
</html>
102. 2.Intelligent Form Flow Control
Automatically Focusing and Blurring Form Elements
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
$("input").blur(function(){
$("input").css("background-color","red");
});
$("input").focus(function(){
$("input").css("background-color","yellow");
});
});
</script></head>
<body>
Enter your name: <input type="text">
</body>
</html>
107. 3.Dynamically Controlling Form Element Appearance and Behavior
● In addition to the intelligent flow control, it is also helpful to provide visual
indicators and these indicators may adjust font or element sizes, change
classes, add/change borders, and so on.
● Many of the changes can be made by simple CSS settings based on element
states, such as :hover or :checked.
● The hover() method specifies two functions to run when the mouse pointer
hovers over the selected elements.
● This method triggers both the mouseenter and mouseleave events.
Note: If only one function is specified, it will be run for both the mouseenter and
mouseleave events.
109. 4.Validating a Form
Manually Validating a Web Form
● The most basic way of validating forms is by accessing their values and checking the
actual contents against the requirements.
● This can be done when the user is entering data by adding, for example, a blur,
change, or keypress event handler, and then inside the event handler checking the
value of the data
● It can also done when the user submits the form by adding the validation to a submit
handler
111. <body>
<form>
Enter your name: <input type="text" id="t1">
<input type="submit" value="submit">
</form>
</body>
</html>
112. Getting the jQuery Validation Plug-In
● As a plug-in, the validator is implemented by loading the .js file after the jQuery.js
file has been loaded. For example:
○ <script type="text/javascript" src="js/jquery.validate.min.js"></script>
● The plug-in can be downloaded from:
○ http://jqueryvalidation.org/
● CDN(content delivery network)
○ https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/jquery.validate.js
● The documentation for the validation plug-in can be found at:
○ http://docs.jquery.com/Plugins/Validation/
113. Applying Simple jQuery Validation Using HTML
● The validator can be implemented in HTML using the class and title attributes.
● The validator uses a set of rules, such as required or email, to validate the form
element.
● Setting the class attribute to one or more of these rules applies the validation when
.validate() is called on the form.
117. Applying Complex Validation
Adding Validation Rules
● The rules method is used to define the different rules that apply to a form element by
referencing the name attribute.
Adding Validation Messages
● The messages attribute of the validation object is used to specify custom messages that
will be applied to the individual rules for the element.
● The messages attribute is also based on the name attribute of the element
Placing Validation Messages
● The validation plug-in places the error messages directly after the element that was
validated
● The jQuery validate errorplacement() function is used to customize the placement of an
error message
118. ● The .validate() method returns a Validator object, which provides several methods
that are valuable for checking form validation.
Validator Object Methods
128. Creating Advanced Web Page Elements in jQuery
1. Adding an Image Gallery
2. Implementing Tables with Sorting and Filters
3. Creating a Tree View
4. Using Overlay Dialogs
5. Implementing a Graphical Equalizer Display
6. Adding Sparkline Graphics