Unit 3 Wad

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

UNIT-3

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.

The jQuery library contains the following features:

 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).

Basic syntax is: $(selector).action()

 A $ sign to define/access jQuery


 A (selector) to "query (or find)" HTML elements
 A jQuery action() to be performed on the element(s)

Examples:

$(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".

Are you familiar with CSS selectors?

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.

The Document Ready Event


You might have noticed that all jQuery methods in our examples, are inside a document
ready event:

$(document).ready(function(){

  // jQuery methods go here...

});

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:

 Trying to hide an element that is not created yet


 Trying to get the size of an image that is not loaded yet

Tip: The jQuery team has also created an even shorter method for the document ready
event:

$(function(){

  // jQuery methods go here...

});

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

The element Selector


The jQuery element selector selects elements based on the element name.

You can select all <p> elements on a page like this:

$("p")

Example

When a user clicks on a button, all <p> elements will be hidden:

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();
  });
});

The .class Selector


The jQuery .class selector finds elements with a specific class.

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

$("*") Selects all elements

$(this) Selects the current HTML element

$("p.intro") Selects all <p> elements with class="intro"

$("p:first") Selects the first <p> element

$("ul li:first") Selects the first <li> element of the first <ul>

$("ul li:first-child") Selects the first <li> element of every <ul>

$("[href]") Selects all elements with an href attribute

$("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"

$(":button") Selects all <button> elements and <input> elements of type="button"

$("tr:even") Selects all even <tr> elements


$("tr:odd") Selects all odd <tr> elements

Use our jQuery Selector Tester to demonstrate the different selectors.

For a complete reference of all the jQuery selectors, please go to our jQuery Selectors
Reference.

Functions In a Separate File


If your website contains a lot of pages, and you want your jQuery functions to be easy to
maintain, you can put your jQuery functions in a separate .js file.

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>

jQuery is tailor-made to respond to events in an HTML page.

What are Events?


All the different visitors' actions that a web page can respond to are called events.

An event represents the precise moment when something happens.

Examples:

 moving a mouse over an element


 selecting a radio button
 clicking on an element
The term "fires/fired" is often used with events. Example: "The keypress event is fired,
the moment you press a key".

Here are some common DOM events:

Mouse Events Keyboard Events Form Events Document/Wind

click keypress submit load

dblclick keydown change resize

mouseenter keyup focus scroll

mouseleave   blur unload

jQuery Syntax For Event Methods


In jQuery, most DOM events have an equivalent jQuery method.

To assign a click event to all paragraphs on a page, you can do this:

$("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()

The $(document).ready() method allows us to execute a function when the document is fully


loaded. This event is already explained in the jQuery Syntax chapter.

click()

The click() method attaches an event handler function to an HTML element.

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 dblclick() method attaches an event handler function to an HTML element.

The function is executed when the user double-clicks on the HTML element:

Example
$("p").dblclick(function(){
  $(this).hide();
});

mouseenter()

The mouseenter() method attaches an event handler function to an HTML element.

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 mousedown() method attaches an event handler function to an HTML element.

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 mouseup() method attaches an event handler function to an HTML element.

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 hover() method takes two functions and is a combination of


the mouseenter() and mouseleave() methods.

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()

The focus() method attaches an event handler function to an HTML form field.

The function is executed when the form field gets focus:

Example
$("input").focus(function(){
  $(this).css("background-color", "#cccccc");
});

blur()

The blur() method attaches an event handler function to an HTML form field.

The function is executed when the form field loses focus:

Example
$("input").blur(function(){
  $(this).css("background-color", "#ffffff");
});

The on() Method


The on() method attaches one or more event handlers for the selected elements.

Attach a click event to a <p> element:

Example
$("p").on("click", function(){
  $(this).hide();
});

Attach multiple event handlers to a <p> element:


Example
$("p").on({
  mouseenter: function(){
    $(this).css("background-color", "lightgray");
  },
  mouseleave: function(){
    $(this).css("background-color", "lightblue");
  },
  click: function(){
    $(this).css("background-color", "yellow");
  }
});
Example program

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.

Simple Example in JSON


The following example shows how to use JSON to store information related to books based on their
topic and edition.
{
"book": [

{
"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>");

var object2 = { "language" : "C++", "author" : "E-Balagurusamy" };


document.write("<br>");
document.write("<h3>Language = " + object2.language+"</h3>");
document.write("<h3>Author = " + object2.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 supports the following two data structures −


 Collection of name/value pairs − This Data Structure is supported by different programming
languages.
 Ordered list of values − It includes array, list, vector or sequence etc.

JSON - DataTypes
JSON format supports the following data types −

Sr.No Type & Description


.

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 −

Sr.No Type & Description


.

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 −

Sr.No Type & Description


.

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 −

 number (integer or floating point)


 string
 boolean
 array
 object
 null
Syntax
String | Number | Object | Array | TRUE | FALSE | NULL
Example
var i = 1;
var j = "sachin";
var k = null;

JSON - Objects
Creating Simple Objects
JSON objects can be created with JavaScript. Let us see the various ways of creating JSON objects
using JavaScript −

 Creation of an empty Object −


var JSONObj = {};

 Creation of a new Object −


var JSONObj = new Object();
 Creation of an object with attribute bookname with value in string, attribute price with numeric
value. Attribute is accessed by using '.' Operator −
var JSONObj = { "bookname ":"VB BLACK BOOK", "price":500 };
This is an example that shows creation of an object in javascript using JSON, save the below code
as json_object.htm −
Live Demo

<html>
<head>
<title>Creating Object JSON with JavaScript</title>
<script language = "javascript" >
var JSONObj = { "name" : "tutorialspoint.com", "year" : 2005 };

document.write("<h1>JSON with JavaScript example</h1>");


document.write("<br>");
document.write("<h3>Website Name = "+JSONObj.name+"</h3>");
document.write("<h3>Year = "+JSONObj.year+"</h3>");
</script>
</head>

<body>
</body>
</html>

Now let's try to open Json Object using IE or any other javaScript enabled browser. It produces the
following result −

Creating Array Objects


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

<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  

Creating Simple Objects


JSON objects can be created with JavaScript. Let us see the various ways of creating JSON objects
using JavaScript −

 Creation of an empty Object −


var JSONObj = {};

 Creation of a new Object −


var JSONObj = new Object();
 Creation of an object with attribute bookname with value in string, attribute price with numeric
value. Attribute is accessed by using '.' Operator −
var JSONObj = { "bookname ":"VB BLACK BOOK", "price":500 };
This is an example that shows creation of an object in javascript using JSON, save the below code
as json_object.htm −
Live Demo

<html>
<head>
<title>Creating Object JSON with JavaScript</title>
<script language = "javascript" >
var JSONObj = { "name" : "tutorialspoint.com", "year" : 2005 };

document.write("<h1>JSON with JavaScript example</h1>");


document.write("<br>");
document.write("<h3>Website Name = "+JSONObj.name+"</h3>");
document.write("<h3>Year = "+JSONObj.year+"</h3>");
</script>
</head>

<body>
</body>
</html>

Now let's try to open Json Object using IE or any other javaScript enabled browser. It produces the
following result −

Creating Array Objects


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

<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 - Comparison with XML

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!

The way JavaScript works

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>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change HTML content.</p>


<button type="button" onclick="document.getElementById('demo').innerHTML = 'Hello
JavaScript!'">Click Me!</button>

</body>
</html>

Selecting elements in in the DOCUMENTS(JavaScript HTML DOM Elements )

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.

Some of the HTML events and their event handlers are:


Example code:
onmouseover and onmouseout
These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and
the onmouseout triggers when you move your mouse out from that element. Try the following
example.
<html>
<head>
<script type = "text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>

<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>

You might also like