Unit 3 Wad
Unit 3 Wad
Unit 3 Wad
JQuery
What is jQuery?
jQuery is a lightweight, "write less, do more", JavaScript library.
The purpose of jQuery is to make it much easier to use JavaScript on your website.
jQuery takes a lot of common tasks that require many lines of JavaScript code to
accomplish, and wraps them into methods that you can call with a single line of code.
jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and
DOM manipulation.
HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
AJAX
Utilities
Tip: In addition, jQuery has plugins for almost any task out there.
Why jQuery?
There are lots of other JavaScript libraries out there, but jQuery is probably the most
popular, and also the most extendable.
Many of the biggest companies on the Web use jQuery, such as:
Google
Microsoft
IBM
Netflix
With jQuery you select (query) HTML elements and perform "actions" on them.
jQuery Syntax
The jQuery syntax is tailor-made for selecting HTML elements and performing
some action on the element(s).
Examples:
jQuery uses CSS syntax to select elements. You will learn more about the selector syntax in
the next chapter of this tutorial.
Tip: If you don't know CSS, you can read our CSS Tutorial.
$(document).ready(function(){
});
This is to prevent any jQuery code from running before the document is finished loading (is
ready).
It is good practice to wait for the document to be fully loaded and ready before working with
it. This also allows you to have your JavaScript code before the body of your document, in
the head section.
Here are some examples of actions that can fail if methods are run before the document is
fully loaded:
Tip: The jQuery team has also created an even shorter method for the document ready
event:
$(function(){
});
jQuery Selectors
jQuery selectors allow you to select and manipulate HTML element(s).
jQuery selectors are used to "find" (or select) HTML elements based on their name, id,
classes, types, attributes, values of attributes and much more. It's based on the
existing CSS Selectors, and in addition, it has some own custom selectors.
All selectors in jQuery start with the dollar sign and parentheses: $().
$("p")
Example
Example
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
The #id Selector
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.
An id should be unique within a page, so you should use the #id selector when you want to
find a single, unique element.
To find an element with a specific id, write a hash character, followed by the id of the HTML
element:
$("#test")
Example
When a user clicks on a button, the element with id="test" will be hidden:
Example
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
To find elements with a specific class, write a period character, followed by the name of the
class:
$(".test")
Example
When a user clicks on a button, the elements with class="test" will be hidden:
Example
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
More Examples of jQuery Selectors
Syntax Description
$("ul li:first") Selects the first <li> element of the first <ul>
$("a[target='_blank']") Selects all <a> elements with a target attribute value equal to "_blank"
$("a[target!='_blank']") Selects all <a> elements with a target attribute value NOT equal to "_blank"
For a complete reference of all the jQuery selectors, please go to our jQuery Selectors
Reference.
When we demonstrate jQuery in this tutorial, the functions are added directly into
the <head> section. However, sometimes it is preferable to place them in a separate file, like
this (use the src attribute to refer to the .js file):
Example
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></scri
pt>
<script src="my_jquery_functions.js"></script>
</head>
Examples:
$("p").click();
The next step is to define what should happen when the event fires. You must pass a
function to the event:
$("p").click(function(){
// action goes here!!
});
Commonly Used jQuery Event Methods
$(document).ready()
click()
The function is executed when the user clicks on the HTML element.
The following example says: When a click event fires on a <p> element; hide the
current <p> element:
Example
$("p").click(function(){
$(this).hide();
});
dblclick()
The function is executed when the user double-clicks on the HTML element:
Example
$("p").dblclick(function(){
$(this).hide();
});
mouseenter()
The function is executed when the mouse pointer enters the HTML element:
Example
$("#p1").mouseenter(function(){
alert("You entered p1!");
});
mouseleave()
The mouseleave() method attaches an event handler function to an HTML element.
The function is executed when the mouse pointer leaves the HTML element:
Example
$("#p1").mouseleave(function(){
alert("Bye! You now leave p1!");
});
mousedown()
The function is executed, when the left, middle or right mouse button is pressed down, while
the mouse is over the HTML element:
Example
$("#p1").mousedown(function(){
alert("Mouse down over p1!");
});
mouseup()
The function is executed, when the left, middle or right mouse button is released, while the
mouse is over the HTML element:
Example
$("#p1").mouseup(function(){
alert("Mouse up over p1!");
});
hover()
The first function is executed when the mouse enters the HTML element, and the second
function is executed when the mouse leaves the HTML element:
Example
$("#p1").hover(function(){
alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});
focus()
Example
$("input").focus(function(){
$(this).css("background-color", "#cccccc");
});
blur()
Example
$("input").blur(function(){
$(this).css("background-color", "#ffffff");
});
Example
$("p").on("click", function(){
$(this).hide();
});
JSON
JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-
readable data interchange. Conventions used by JSON are known to programmers, which include C,
C++, Java, Python, Perl, etc.
JSON stands for JavaScript Object Notation.
The format was specified by Douglas Crockford.
It was designed for human-readable data interchange.
It has been extended from the JavaScript scripting language.
The filename extension is .json.
JSON Internet Media type is application/json.
The Uniform Type Identifier is public.json.
Uses of JSON
It is used while writing JavaScript based applications that includes browser extensions and
websites.
JSON format is used for serializing and transmitting structured data over network connection.
It is primarily used to transmit data between a server and web applications.
Web services and APIs use JSON format to provide public data.
It can be used with modern programming languages.
Characteristics of JSON
JSON is easy to read and write.
It is a lightweight text-based interchange format.
JSON is language independent.
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id":"07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
}
After understanding the above program, we will try another example. Let's save the below code
as json.htm −
Live Demo
<html>
<head>
<title>JSON example</title>
<script language = "javascript" >
var object1 = { "language" : "Java", "author" : "herbert schildt" };
document.write("<h1>JSON with JavaScript example</h1>");
document.write("<br>");
document.write("<h3>Language = " + object1.language+"</h3>");
document.write("<h3>Author = " + object1.author+"</h3>");
document.write("<hr />");
document.write(object2.language + " programming language can be
studied " + "from book written by " + object2.author);
document.write("<hr />");
</script>
</head>
<body>
</body>
</html>
JSON - Syntax
Let's have a quick look at the basic syntax of JSON. JSON syntax is basically considered as a
subset of JavaScript syntax; it includes the following −
Data is represented in name/value pairs.
Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are
separated by , (comma).
Square brackets hold arrays and values are separated by ,(comma).
Below is a simple example −
{
"book": [
{
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id": "07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
}
JSON - DataTypes
JSON format supports the following data types −
1
Number
double- precision floating-point format in JavaScript
2
String
double-quoted Unicode with backslash escaping
3
Boolean
true or false
4
Array
an ordered sequence of values
5
Value
it can be a string, a number, true or false, null etc
6
Object
an unordered collection of key:value pairs
7
Whitespace
can be used between any pair of tokens
8
null
empty
Number
It is a double precision floating-point format in JavaScript and it depends on implementation.
Octal and hexadecimal formats are not used.
No NaN or Infinity is used in Number.
The following table shows the number types −
1
Integer
Digits 1-9, 0 and positive or negative
2
Fraction
Fractions like .3, .9
3
Exponent
Exponent like e, e+, e-, E, E+, E-
Syntax
var json-object-name = { string : number_value, .......}
Example
Example showing Number Datatype, value should not be quoted −
var obj = {marks: 97}
String
It is a sequence of zero or more double quoted Unicode characters with backslash escaping.
Character is a single character string i.e. a string with length 1.
The table shows various special characters that you can use in strings of a JSON document −
1
"
double quotation
2
\
backslash
3
/
forward slash
4
b
backspace
5
f
form feed
6
n
new line
7
r
carriage return
8
t
horizontal tab
9
u
four hexadecimal digits
Syntax
var json-object-name = { string : "string value", .......}
Example
Example showing String Datatype −
var obj = {name: 'Amit'}
Boolean
It includes true or false values.
Syntax
var json-object-name = { string : true/false, .......}
Example
var obj = {name: 'Amit', marks: 97, distinction: true}
Array
It is an ordered collection of values.
These are enclosed in square brackets which means that array begins with .[. and ends
with .]..
The values are separated by , (comma).
Array indexing can be started at 0 or 1.
Arrays should be used when the key names are sequential integers.
Syntax
[ value, .......]
Example
Example showing array containing multiple objects −
{
"books": [
{ "language":"Java" , "edition":"second" },
{ "language":"C++" , "lastName":"fifth" },
{ "language":"C" , "lastName":"third" }
]
}
Object
It is an unordered set of name/value pairs.
Objects are enclosed in curly braces that is, it starts with '{' and ends with '}'.
Each name is followed by ':'(colon) and the key/value pairs are separated by , (comma).
The keys must be strings and should be different from each other.
Objects should be used when the key names are arbitrary strings.
Syntax
{ string : value, .......}
Example
Example showing Object −
{
"id": "011A",
"language": "JAVA",
"price": 500,
}
Whitespace
It can be inserted between any pair of tokens. It can be added to make a code more readable.
Example shows declaration with and without whitespace −
Syntax
{string:" ",....}
Example
var obj1 = {"name": "Sachin Tendulkar"}
var obj2 = {"name": "SauravGanguly"}
null
It means empty type.
Syntax
null
Example
var i = null;
if(i == 1) {
document.write("<h1>value is 1</h1>");
} else {
document.write("<h1>value is null</h1>");
}
JSON Value
It includes −
JSON - Objects
Creating Simple Objects
JSON objects can be created with JavaScript. Let us see the various ways of creating JSON objects
using JavaScript −
<html>
<head>
<title>Creating Object JSON with JavaScript</title>
<script language = "javascript" >
var JSONObj = { "name" : "tutorialspoint.com", "year" : 2005 };
<body>
</body>
</html>
Now let's try to open Json Object using IE or any other javaScript enabled browser. It produces the
following result −
<html>
<head>
<title>Creation of array object in javascript using JSON</title>
<script language = "javascript" >
document.writeln("<h2>JSON array object</h2>");
var books = { "Pascal" : [
{ "Name" : "Pascal Made Simple", "price" : 700 },
{ "Name" : "Guide to Pascal", "price" : 400 }],
"Scala" : [
{ "Name" : "Scala for the Impatient", "price" : 1000 },
{ "Name" : "Scala in Depth", "price" : 1300 }]
}
var i = 0
document.writeln("<table border = '2'><tr>");
for(i = 0;i<books.Pascal.length;i++) {
document.writeln("<td>");
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td><b>Name</b></td><td width = 50>" +
books.Pascal[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width = 50>" +
books.Pascal[i].price +"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
for(i = 0;i<books.Scala.length;i++) {
document.writeln("<td>");
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td><b>Name</b></td><td width = 50>" +
books.Scala[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width = 50>" +
books.Scala[i].price+"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
document.writeln("</tr></table>");
</script>
</head>
<body>
</body>
</html>
Now let's try to open Json Array Object using IE or any other javaScript enabled browser. It
produces the following result −
JSON - Objects
Advertisements
Previous Page
Next Page
<html>
<head>
<title>Creating Object JSON with JavaScript</title>
<script language = "javascript" >
var JSONObj = { "name" : "tutorialspoint.com", "year" : 2005 };
<body>
</body>
</html>
Now let's try to open Json Object using IE or any other javaScript enabled browser. It produces the
following result −
<html>
<head>
<title>Creation of array object in javascript using JSON</title>
<script language = "javascript" >
document.writeln("<h2>JSON array object</h2>");
var books = { "Pascal" : [
{ "Name" : "Pascal Made Simple", "price" : 700 },
{ "Name" : "Guide to Pascal", "price" : 400 }],
"Scala" : [
{ "Name" : "Scala for the Impatient", "price" : 1000 },
{ "Name" : "Scala in Depth", "price" : 1300 }]
}
var i = 0
document.writeln("<table border = '2'><tr>");
for(i = 0;i<books.Pascal.length;i++) {
document.writeln("<td>");
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td><b>Name</b></td><td width = 50>" +
books.Pascal[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width = 50>" +
books.Pascal[i].price +"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
for(i = 0;i<books.Scala.length;i++) {
document.writeln("<td>");
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td><b>Name</b></td><td width = 50>" +
books.Scala[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width = 50>" +
books.Scala[i].price+"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
document.writeln("</tr></table>");
</script>
</head>
<body>
</body>
</html>
Now let's try to open Json Array Object using IE or any other javaScript enabled browser. It
produces the following result −
JSON and XML are human readable formats and are language independent. They both have
support for creation, reading and decoding in real world situations. We can compare JSON with
XML, based on the following factors −
Verbose
XML is more verbose than JSON, so it is faster to write JSON for programmers.
Arrays Usage
XML is used to describe the structured data, which doesn't include arrays whereas JSON include
arrays.
Parsing
JavaScript's eval method parses JSON. When applied to JSON, eval returns the described object.
Example
Individual examples of XML and JSON −
JSON
{
"company": Volkswagen,
"name": "Vento",
"price": 800000
}
XML
<car>
<company>Volkswagen</company>
<name>Vento</name>
<price>800000</price>
</car>
JAVASCRIPT:
JavaScript gives you superpowers. The true programming language of the web, JavaScript lets you add behavior to your
web pages. No more dry, boring, static pages that just sit there looking at you—with JavaScript you’re going to be able
to reach out and touch your users, react to interesting events, grab data from the web to use in your pages, draw
graphics right in your web pages and a lot more. And once you know JavaScript you’ll also be in a position to create
totally new behaviors for your users. You’ll be in good company too, JavaScript’s not only one of the most popular
programming languages, it’s also supported in all modern (and most ancient) browsers; JavaScript’s even branching out
and being embedded in a lot of environments outside the browser. More on that later; for now, let’s get started!
If you’re used to creating structure, content, layout and style in your web pages, isn’t it time to add a little behavior as
well? These days, there’s no need for the page to just sit there. Great pages should be dynamic, interactive, and they
should work with your users in new ways. That’s where JavaScript comes in.
How to get JavaScript into your page First things first. You can’t get very far with JavaScript if you don’t know how to get
it into a page. So, how do you do that? Using the
The source code is passed through a program called a compiler, which translates it into bytecode
that the machine understands and can execute. In contrast, JavaScript has no compilation step.
Instead, an interpreter in the browser reads over the JavaScript code, interprets each line, and
runs it.
Ex program:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Using getElementById():
Using getElementByName():
Using getElementByTagName():
Using getElementByClassName():
JavaScript Events
The change in the state of an object is known as an Event. In html, there are various events which
represents that some activity is performed by the user or by the browser. When javascript code is
included in HTML, js react over these events and allow the execution. This process of reacting over
the events is called Event Handling. Thus, js handles the HTML events via Event Handlers.
For example, when a user clicks over the browser, add js code, which will execute the task to be
performed on the event.
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>