FSD Unit2
FSD Unit2
Our JavaScript Tutorial is designed for beginners and professionals both. JavaScript is usedto
create client-side dynamic pages.
JavaScript is an object-based scripting language which is lightweight and cross-platform.
JavaScript is not a compiled language, but it is a translated language. The JavaScript Translator
(embedded in the browser) is responsible for translating the JavaScript code forthe web browser.
What is JavaScript
Although, JavaScript has no connectivity with Java programming language. The name was
suggested and provided in the times when Java was gaining popularity in the market. In addition to
web browsers, databases such as CouchDB and MongoDB uses JavaScript as theirscripting and
query language.
Features of JavaScript
1. All popular web browsers support JavaScript as they provide built-in execution environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is a
structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast (depending onthe
operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather than using
classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS, etc.
8. It provides good control to the users over the web browsers.
1
History of JavaScript
In 1993, Mosaic, the first popular web browser, came into existence. In the year 1994, Netscape
was founded by Marc Andreessen. He realized that the web needed to become more dynamic.
Thus, a 'glue language' was believed to be provided to HTML to make web designing easy for
designers and part-time programmers. Consequently, in 1995, the company recruited Brendan
Eich intending to implement and embed Scheme programming language to the browser. But,
before Brendan could start, the company merged with Sun Microsystems for adding Java into its
Navigator so that it could compete with Microsoft overthe web technologies and platforms. Now,
two languages were there: Java and the scripting language. Further, Netscape decided to give a
similar name to the scripting language as Java's. It led to 'Javascript'. Finally, in May 1995, Marc
Andreessen coined the first code of Javascript named 'Mocha'. Later, the marketing team replaced
the name with 'LiveScript'.
But, due to trademark reasons and certain other reasons, in December 1995, the language was
finally renamed to 'JavaScript'. From then, JavaScript came into existence.
Application of JavaScript
Client-side validation,
Dynamic drop-down menus,
Displaying date and time,
Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog boxand
prompt dialog box),
Displaying clocks etc.
JavaScript Example
<script>
document.write("Hello JavaScript by JavaScript");
</script>
JavaScript Example
Javascript example is easy to code. JavaScript provides 3 places to put the JavaScript code:
within body tag, within head tag and external JavaScript file.
<script type="text/javascript">
document.write("JavaScript is a simple language for javatpoint learners");
</script>
The script tag specifies that we are using JavaScript.
The text/javascript is the content type that provides information to the browser about the data.
The document.write() function is used to display dynamic content through JavaScript.
2
JavaScript Example : code between the body tag
In the above example, we have displayed the dynamic content using JavaScript. Let’s see thesimple
example of JavaScript that displays alert dialog box.
1. <script type="text/javascript">
2. alert("Hello Javatpoint");
3. </script>
JavaScript Example : code between the head tag
Let’s see the same example of displaying alert dialog box of JavaScript that is contained inside
the head tag.
In this example, we are creating a function msg(). To create function in JavaScript, you needto
write function with function_name as given below.
To call function, you need to work on event. Here we are using onclick event to call msg() function.
1. <html>
2. <head>
3. <script type="text/javascript">
4. function msg(){
5. alert("Hello Javatpoint");6.
}
6. </script>
7. </head>
8. <body>
9. <p>Welcome to JavaScript</p>
10. <form>
11. <input type="button" value="click" onclick="msg()"/>
12. </form>
13. </body>
14. </html>
We can create external JavaScript file and embed it in many html page.
It provides code re usability because single JavaScript file can be used in several html pages.
An external JavaScript file must be saved by .js extension. It is recommended to embed allJavaScript
files into a single file. It increases the speed of the webpage.
Let's create an external JavaScript file that prints Hello Javatpoint in a alert dialog box.
message.js
1. function msg(){
2. alert("Hello Javatpoint");3. }
Let's include the JavaScript file into html page. It calls the JavaScript function on buttonclick.
index.html
1. <html>
3
2. <head>
3. <script type="text/javascript" src="message.js"></script>
4. </head>
5. <body>
6. <p>Welcome to JavaScript</p>
7. <form>
8. <input type="button" value="click" onclick="msg()"/>
9. </form>
10. </body>
11. </html>
1. The stealer may download the coder's code using the url of the js file.
2. If two js files are dependent on one another, then a failure in one file may affect the
execution of the other dependent file.
3. The web browser needs to make an additional http request to get the js code.
4. A tiny to a large change in the js code may cause unexpected results in all its
dependent files.
5. We need to check each file that depends on the commonly created external javascript file.
6. If it is a few lines of code, then better to implement the internal javascript code.
JavaScript Comment
1. JavaScript comments
2. Advantage of javaScript comments
3. Single-line and Multi-line comments
The JavaScript comments are meaningful way to deliver message. It is used to add information
about the code, warnings or suggestions so that end user can easily interpret thecode.
The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.
1. To make code easy to understand It can be used to elaborate the code so that end user can easily
understand the code.
2. To avoid the unnecessary code It can also be used to avoid the code being executed. Sometimes,
4
we add the code to perform some action. But after sometime, there may be needto disable the code.
In such case, it is better to use comments.
Types of JavaScript Comments
1. Single-line Comment
2. Multi-line Comment
It is represented by double forward slashes (//). It can be used before and after the statement. Let’s
see the example of single-line comment i.e. added before the statement.
1. <script>
2. // It is single line comment
3. document.write("hello javascript");
4. </script>
Let’s see the example of single-line comment i.e. added after the statement.
1. <script>
2. var a=10;
3. var b=20;
4. var c=a+b;//It adds values of a and b variable
5. document.write(c);//prints sum of 10 and 20
6. </script>
It can be used to add single as well as multi line comments. So, it is more convenient.
It is represented by forward slash with asterisk then asterisk with forward slash. For example:
1. <script>
2. /* It is multi line comment.
3. It will not be displayed */
4. document.write("example of javascript multiline comment");
5. </script>
JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types of variables in
JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
5
1. var x = 10;
2. var _value="sonoo";
1. var 123=30;
2. var *aa=320;
1. <script>
2. var x = 10;
3. var y = 20;
4. var z=x+y;
5. document.write(z);
6. </script>
30
<script>
function abc(){
var x=10;//local variable
}
</script>
<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>
1. <script>
2. var data=200;//gloabal variable
3. function a(){
4. document.writeln(data);
5. }
6. function b(){
7. document.writeln(data);
6
8. }
9. a();//calling JavaScript function
10. b();
11. </script>
A JavaScript global variable is declared outside the function or declared with window
object. It can be accessed from any function.
Let’s see the simple example of global variable in JavaScript.
1. <script>
2. var value=50;//global variable
3. function a(){
4. alert(value);
5. }
6. function b(){
7. alert(value);
8. }
9. </script>
To declare JavaScript global variables inside function, you need to use window object.
For example:
1. window.value=90;
Now it can be declared inside any function and can be accessed from any function. For example:
4. function m(){
5. window.value=100;//declaring global variable by window object
6. }
7. function n(){
8. alert(window.value);//accessing global variable from other function
6. }
When you declare a variable outside the function, it is added in the window object internally. You can
access it through window object also. For example:
1. var value=50;
2. function a(){
3. alert(window.value);//accessing global variable
4. }
Objects
Objects are the basic run-time bodies in an object-oriented framework. They may represent a place,
a person, an account, a table of data, or anything that the program needs to handle.
Objects can also represent user-defined data such as vectors, time, and lists.
Consider two objects, “customer” and “account” in a program. The customer object may senda
message requesting the bank balance.
Classes
We know that objects hold the data and the functions to manipulate the data. However, the two
can be bound together in a user-defined data type with the help of classes. Any numberof objects
can be created in a class. Each object is associated with the data of type class. A class is therefore
a collection of objects of similar types.
For example, consider the class “Fruits”. We can create multiple objects for this class -Fruit
Mango;
This will create an object mango belonging to the class fruit.
Encapsulation
Encapsulation is the wrapping up/binding of data and function into a single unit called class. Data
encapsulation is the most prominent feature of a class wherein the data is not accessibleto the
outside world, and only those functions wrapped inside the class can access it. These functions
serve as the interface between the object’s data and the program.
Inheritance
The phenomenon where objects of one class acquire the properties of objects of another class is
called Inheritance. It supports the concept of hierarchical classification. Consider the object “car”
that falls in the class “Vehicles” and “Light Weight Vehicles”.
In OOP, the concept of inheritance ensures reusability. This means that additional features can
be added to an existing class without modifying it. This is made possible by deriving a new class
from the existing one.
OOP Concepts in JavaScript
JavaScript Objects
In JavaScript, almost "everything" is an object.
Example
let person = "John Doe";
Objects are variables too. But objects can contain many values.
Object values are written as name : value pairs (name and value separated by a colon).
Example
let person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Example
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Object Properties
The named values, in JavaScript objects, are called properties.
Properties Values
firstName John
lastName Doe
age 20
eyeColor blue
Object Methods
Methods are actions that can be performed on objects.
Object properties can be both primitive values, other objects, and functions.
An object method is an object property containing a function definition.
Properties Values
firstName John
lastName Doe
age 20
eyeColor blue
9
fullName function() {return this.firstName + " " +
this.lastName;}
The following example creates a new JavaScript object with four properties:
Example
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
var student = {
name: "pp", age:
21,
studies: "Computer Science",
};
What is this?
In JavaScript, the this keyword refers to an object.
Methods like call(), apply(), and bind() can refer this to any object.
Note
this is not a variable. It is a keyword. You cannot change the value of this.
Syntax
class ClassName {
constructor() { ... }
}
Example
11
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
Using a Class
When you have a class, you can use the class to create objects:
Example
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
The example above uses the Car class to create two Car objects.
If you do not define a constructor method, JavaScript will add an empty constructor method.
Class Methods
Class methods are created with the same syntax as object methods.
Use the keyword class to create a class.
Always add a constructor() method.
Then add any number of methods.
Syntax
class ClassName {
constructor() { ... }
method_1() { ... }
method_2() { ... }
method_3() { ... }
}
}
}
let car1 = new Cars('Rolls Royce Ghost', 'Rolls Royce', '$315K'); let car2 =
new Cars('Mercedes AMG One', 'Mercedes', '$2700K');
console.log(car1.name);
console.log(car2.maker);
console.log(car1.getDetails());
Encapsulation in JavaScript
Encapsulation includes wrapping the property and the function within a single unit. Consider the
following example:
Class Emp_details{
constructor(name,id){
this.name = name;
this.id = id;
}
add_Address(add){
this.add = add;
}
getDetails(){
Class Inheritance
To create a class inheritance, use the extends keyword.
A class created with a class inheritance inherits all the methods from another class:
13
Example
Create a class named "Model" which will inherit the methods from the "Car" class:
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}
By calling the super() method in the constructor method, we call the parent's constructor method and gets
access to the parent's properties and methods.
Inheritance is useful for code reusability: reuse properties and methods of an existing class when you create
a new class.
Memory management is an essential task when writing a good and effective program in some
programming languages. This article will help you to understand different concepts of memory
management in JavaScript. In low-level languages like C and C++, programmers should care about
the usage of memory in some manual fashion. On the other hand, Javascript automatically allocates
memory when objects are created into the environment andalso it cleans the memory when an object
is destroyed. JavaScript can manage all of these on its own but this does not imply that the
developers do not need to worry about the memory management in JavaScript.
Memory management in any programming language involves three important phases, termedas
memory life-cycle −
14
Stack: It is a data structure used to store static data. Static data refers to data whose size is
known by the engine during compile time. In JavaScript, static data includes primitive values
like strings, numbers, boolean, null, and undefined. References that point to objects and
functions are also included. A fixed amount of memory is allocated for static data. This process
is known as static memory allocation.
Heap: It is used to store objects and functions in JavaScript. The engine doesn’t allocate a
fixed amount of memory. Instead, it allocates more space as required.
Overview:
Stack Heap
Example:
Javascript
const employee = {
name: 'Rajesh',
age: 30,
};
const name="Ram"
function getname(name) {
return name;
}
// The function return value is given to stack after
// being evaluated in the heap
/* The newEmployee object will be stored in the stack and it will refer to the employee
object in heap */
Explanation: In the above example object ’employee’ is created in the heap and a reference to it in
the stack.
15
Memory Management in JavaScript
Different Strategies to Allocate Memory in JavaScript
Allocation in JavaScript
Value initialization
In order to not bother the programmer with allocations, JavaScript will automatically allocate
memory when values are initially declared.
var s1 = 'sessionstack';
var s2 = s1.substr(0, 3); // s2 is a new string
// Since strings are immutable,
// JavaScript may decide to not allocate memory,
// but just store the [0, 3] range.var a1 = ['str1', 'str2'];
var a2 = ['str3', 'str4'];
var a3 = a1.concat(a2);
16
// new array with 4 elements being
// the concatenation of a1 and a2 elements
Using memory in JavaScript
Using the allocated memory in JavaScript basically, means reading and writing in it.
This can be done by reading or writing the value of a variable or an object property or even passing an
argument to a function.
Release when the memory is not needed anymore
Most of the memory management issues come at this stage.
The hardest task here is to figure out when the allocated memory is not needed any longer. It
often requires the developer to determine where in the program such piece of memory is not
needed anymore and free it.
High-level languages embed a piece of software called garbage collector which job is to track
memory allocation and use in order to find when a piece of allocated memory is not needed
any longer in which case, it will automatically free it.
Unfortunately, this process is an approximation since the general problem of knowing whether
some piece of memory is needed is undecidable (can’t be solved by an algorithm).
Most garbage collectors work by collecting memory which can no longer be accessed, e.g. all
variables pointing to it went out of scope. That’s, however, an under-approximation of the set
of memory spaces that can be collected, because at any point a memory location may still have
a variable pointing to it in scope, yet it will never be accessed again.
Garbage Collection: Garbage collectors are used in releasing memory. Once the engine
recognizes that a variable, object, or function is not needed anymore, it releases the memory it
occupied. The main issue here is that it is very difficult to predict accurately whether a particular
variable, object, or function is needed anymore or not. Some algorithms help to find the moment
when they become obsolete with great precision.
References
The main concept that garbage collection algorithms rely on is the concept of reference. Within the
context of memory management, an object is said to reference another object if the former has access
to the latter (either implicitly or explicitly). For instance, a JavaScript object has a reference to
its prototype (implicit reference) and to its properties values (explicit reference).
In this context, the notion of an "object" is extended to something broader than regular JavaScript
objects and also contain function scopes (or the global lexical scope).
Reference-counting garbage collection: It frees the memory allocated to the objects that have no
references pointing to them. However, the problem with this algorithm is that it doesn’t understand
cyclic references.
Example: Javascript
let game = {
name: 'cricket',
};
let boy = {
name: 'Ram',
}
game.boy = boy;
boy.game = game;
boy = null;
game = null;
17
Explanation: In this example, the game and boy both reference each other. Thus, the algorithm
won’t release the allocated memory. Setting them to null won’t make the algorithm realize that
they can’t be used anymore, leading to no release of allocated memory.
Mark-and-sweep algorithm: This algorithm solves the above-mentioned issue. Instead of finding
references to a particular object, it detects if they are reachable from the root object.
Note: In JavaScript root is the window object while in NodeJS it is the global object.
The algorithm marks objects that are not reachable as garbage and collects (sweeps) them. Thus, it
is known as Mark and Sweep algorithm. In the previous example, neither the game nor the boy
object can be accessed from the root object. Thus, it is marked as garbage and collected afterwards.
Using previously allocated memory is just reading or writing values from some variables which are
assigned previously. We can update its existing value with some other values.
When our purpose is served, we can remove the allocated memory block. In some low-level
languages, this is a necessary step, otherwise, it may occupy memory spaces over time and the total
system may crash. JavaScript also has native support of Garbage Collector, which cleans
unnecessary memory blocks and cleans up the memory. But sometimes the compiler cannot
understand whether a block will be used in later cases or not. In such cases, the Garbage Collector
does not clean up that memory. To manually remove allocated locations, we can use the ‘delete’
keyword before the variable name.
Syntax
delete <variable_name>
const Employee = {
firstname: 'John',
lastname: 'Doe',
};
console.log(Employee.firstname);
// Expected output: "John"
18
delete Employee.firstname;
console.log(Employee.firstname);
// Expected output: undefined
The variable must be allocated beforehand, otherwise, it will raise an error while trying to delete
that variable.
Note − The ‘delete’ keyword will only work when the variable is allocated directly (without using the
var or let keyword).
Conclusion
Working with any programming language, the programmer should know the overall concept in depth.
Memory management is one of the concerning issues, in which developers should properly manage
the memory otherwise it will occupy unnecessary memory blocks and createmajor problems in the
environment. JavaScript provides an additional garbage collector tool that automatically cleans the
unused memory blocks. However, we can also deallocate memory by using the ‘delete’ keyword just
before the variable name
A browser built-in XMLHttpRequest object (to request data from a web server)
JavaScript and HTML DOM (to display or use the data)
AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the
scenes
19
1. An event occurs in a web page (the page is loaded, a button is clicked)
2. An XMLHttpRequest object is created by JavaScript
3. The XMLHttpRequest object sends a request to a web server
4. The server processes the request
5. The server sends a response back to the web page
6. The response is read by JavaScript
7. Proper action (like page update) is performed by JavaScript
The XMLHttpRequest object can be used to exchange data with a server behind the scenes. This means
that it is possible to update parts of a web page, without reloading the whole page.
Example
var xhttp = new XMLHttpRequest();
Method Description
20
send(string) Sends the request to the server.
Used for POST requests
Property Description
GET or POST?
GET is simpler and faster than POST, and can be used in most cases.
21
Sending user input (which can contain unknown characters), POST is more robust and secure
than GET.
GET Requests
A simple GET request:
Example
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();
In the example above, you may get a cached result. To avoid this, add a unique ID to the URL:
POST Requests
A simple POST request:
Example
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();
To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the data you
want to send in the send() method:
Example
xhttp.open("POST", "demo_post2.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");
The file can be any kind of file, like .txt and .xml, or server scripting files like .asp and .php (which can
perform actions on the server before sending the response back).
22
The function is defined in the onreadystatechange property of the XMLHttpResponse object:
Example
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
The "ajax_info.txt" file used in the example above, is a simple text file and looks like this:
<h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web page.</p>
<p>AJAX stands for Asynchronous JavaScript And XML.</p>
Synchronous Request
To execute a synchronous request, change the third parameter in the open() method to false:
Sometimes async = false are used for quick testing. You will also find synchronous requests in older
JavaScript code.
Since the code will wait for server completion, there is no need for an onreadystatechange function:
The onreadystatechange property defines a function to be executed when the readyState changes.
The status property and the statusText property holds the status of the XMLHttpRequest object.
Example
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
23
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
The "ajax_info.txt" file used in the example above, is a simple text file and looks like this:
<h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web page.</p>
<p>AJAX stands for Asynchronous JavaScript And XML.</p>
The onreadystatechange event is triggered four times (1-4), one time for each change in the readyState.
getAllResponseHeaders() Returns all the header information from the server resource
The responseText Property
The responseText property returns the server response as a JavaScript string, and you can use it
accordingly:
Example
document.getElementById("demo").innerHTML = xhttp.responseText;
The responseXML property returns the server response as an XML DOM object.
Using this property you can parse the response as an XML DOM object:
Example
Request the file cd_catalog.xml and parse the response:
xmlDoc = xhttp.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("ARTIST");
24
for (i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();
Example
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getAllResponseHeaders();
}
};
Example
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getResponseHeader("Last-Modified");
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
jQuery Framework
What is jQuery?
jQuery is a JavaScript framework. It facilitates the readability and the manipulation of HTML
DOM elements, event handling, animations, and AJAX calls. It’s also free, open-source
software that adheres to the MIT License. As a result, it is one of the most popular JavaScript
libraries.
The syntax of jQuery makes document navigation, DOM component selection, animation
creation, event handling, and Ajax app development easier.
It allows developers to create plug-ins that operate on top of the JavaScript library.
Developers may use this to construct abstractions for low-level interaction and animation,
complex effects, and themeable widgets at a high level.
The modular nature of the jQuery framework allows developers to create complex dynamic
web pages and apps.
25
What is jQuery used for?
jQuery is an open-source JavaScript library. So when we need to write less and get more
done, it’s light and convenient.
jQuery is a library that covers several common activities that require a lot of JavaScript code
in different methods. Programmers may use a single line of code to invoke this function. As a
consequence, including JavaScript in your website is straightforward. JavaScript is an
independent programming language, whereas jQuery is a collection of JavaScript code (not
its own language).
JQuery is a compact, quick JavaScript library packaged in a single.js file. It has several built-
in functionalities that allow you to complete various activities fast and efficiently.
There are several ways to start using jQuery on your web site. You can:
Downloading jQuery
Production version - this is for your live website because it has been minified and compressed
Development version - this is for testing and development (uncompressed and readable code)
The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag (notice
that the <script> tag should be inside the <head> section):
<head>
<script src="jquery-3.7.1.min.js"></script>
</head>
Tip: Place the downloaded file in the same directory as the pages where you wish to use it.
jQuery CDN
If you don't want to download and host jQuery yourself, you can include it from a CDN (Content
Delivery Network).
26
Google is an example of someone who host jQuery:
Google CDN:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
jQuery Syntax
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.
You might have noticed that all jQuery methods in our examples, are inside a document ready event:
$(document).ready(function(){
});
This is to prevent any jQuery code from running before the document is finished loading (is ready).
27
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 are one of the most important parts of the jQuery library.
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.
$("p")
Example
Example
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
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.
28
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
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
</script>
</head>
<body>
<button>Click me</button>
</body>
</html>
29
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.
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.7.1/jquery.min.js"></script>
<script src="my_jquery_functions.js"></script>
</head>
30
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.7.1/jquery.min.js"></script>
<script src="my_jquery_functions.js"></script>
</head>
jQuery Events
$("p").click(function(){
// action goes here!!
});
31
Commonly Used jQuery Event Methods
$(document).ready()
The $(document).ready() method allows us to execute a function when the document is fully loaded..
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
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").dblclick(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<p>If you double-click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>
</body>
</html>
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
32
$("#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");
});
33
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");
}
});
UI components
UI components are responsible for interactions between the user and the application. They facilitate
an effective user experience, and they allow the users to navigate through the application easily. UI
components also help them to efficiently perform various functions, like adding/editing information,
filtering data, and selecting a date on the calendar.
You can easily create UI components for your JavaScript web application using Sencha Ext JS. It is
the most comprehensive framework for building data-intensive apps for all modern devices.
34
The UI of Ext JS applications is made up of widgets. They are known as components, and they are
subclasses of the Ext.Component class. You can easily extend them to create a customized
component for your web application.
This is a simple login form that accepts the user ID and password. To create it, you have to follow
these simple steps:
1. First, you have to define a new custom class, called KitchenSink.view.form.LoginForm. Then
you have to extend Ext.form.Panel. You also need to define the type of UI component, which
is form-login.
Ext.define('KitchenSink.view.form.LoginForm', {
extend: 'Ext.form.Panel',
xtype: 'form-login',
2. Next, you have to specify title, frame, width, bodyPadding, and defaultType fields.
title: 'Login',
frame:true,
width: 320,
bodyPadding: 10,
defaultType: 'textfield',
3. Then you have to specify the items for “user ID”, “password”, and “Remember me” fields of the
form.
items: [{
allowBlank: false,
fieldLabel: 'User ID',
35
name: 'user',
emptyText: 'user id'
}, {
allowBlank: false,
fieldLabel: 'Password',
name: 'pass',
emptyText: 'password',
inputType: 'password'
}, {
xtype:'checkbox',
fieldLabel: 'Remember me',
name: 'remember'
}],
4. Now, you have to specify the Register and Login buttons.
buttons: [
{ text:'Register' },
{ text:'Login' }
],
5. Finally, you have to specify the defaults.
defaults: {
anchor: '100%',
labelWidth: 120
}
});
*
The JSON syntax is derived from JavaScript object notation, but the JSON format is text only.
Code for reading and generating JSON exists in many programming languages.
You can receive pure text from a server and use it as a JavaScript object.
You can work with data as JavaScript objects, with no complicated parsing and translations.
Storing Data
When storing data, the data has to be a certain format, and regardless of where you choose to store
it, text is always one of the legal formats.
JSON Syntax
A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:
Example
"name":"John"
JSON
{"name":"John"}
37
JavaScript
{name:"John"}
a string
a number
an object (JSON object)
an array
a boolean
null
a function
a date
undefined
JSON Strings
Example
{"name":"John"}
JSON Numbers
Example
{"age":30}
JavaScript Objects
Because JSON syntax is derived from JavaScript object notation, very little extra software is needed to
work with JSON within JavaScript.
With JavaScript you can create an object and assign data to it, like this:
Example
person = {name:"John", age:31, city:"New York"};
Example
38
// returns John
person.name;
Example
// returns John
person["name"];
Example
person.name = "Gilbert";
Example
person["name"] = "Gilbert";
<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
</body>
</html>
JSON Arrays
Example
{
"employees":["John", "Anna", "Peter"]
}
JSON Booleans
Example
{"sale":true}
JSON null
Example
{"middlename":null}
JSON Files
JSON.parse()
When receiving data from a web server, the data is always a string.
Parse the data with JSON.parse(), and the data becomes a JavaScript object.
Use the JavaScript function JSON.parse() to convert text into a JavaScript object:
40
const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');
Array as JSON
When using the JSON.parse() on a JSON derived from an array, the method will return a JavaScript
array, instead of a JavaScript object.
Example
JSON.stringify()
Example
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);
41