Unit-4 JavaScript & JQuery
Unit-4 JavaScript & JQuery
• For a Web page, HTML supplies document content and structure while CSS
provides presentation styling.
• In addition, client-side scripts can control browser actions associated with a Web
page.
• Client-side scripting can make Web pages more dynamic and more responsive
• What can JavaScript do?
• JavaScript can dynamically modify an HTML page.
• JavaScript can validate user input.
• Javascript is a full-featured programming language.
• JavaScript can be used to create cookies
• JavaScript user interaction does not require any communication with the server.
Advantages: Disadvantages:
• Speed. Client-side JavaScript is very • Client-Side Security. Because the
fast because it can be run code executes on the users’
immediately within the client-side computer, in some cases it can be
browser. Unless outside resources exploited for malicious purposes. This
are required, JavaScript is is one reason some people choose to
unhindered by network calls to a disable Javascript.
backend server. • Browser Support. JavaScript is
• Simplicity. JavaScript is relatively sometimes interpreted differently by
simple to learn and implement. different browsers. This makes it
somewhat difficult to write cross-
• Popularity. JavaScript is used browser code.
everywhere on the web.
• Gives the ability to create rich
interfaces.
Difference
Structure of JavaScript
• JavaScript can be implemented using JavaScript statements that are placed
within the <script>…</script>HTML tags in a web page.
• You can place the <script> tag tags, containing your JavaScript, anywhere
within you web page, but it is normally recommended that you should keep it
within the <head> tags.
• JavaScript syntax will look as follows:
<script language =”javascript” type=”text/javascript”>
//javascript code here
</script>
Example: Internal JavaScript
<html>
<body>
<script>
[Link]("Hello JavaScript by JavaScript");
</script>
</body>
</html>
Output:
Example: External JavaScript
• An external JavaScript file must be saved by .js extension. It is
recommended to embed all JavaScript files into a single file. It increases
the speed of the webpage.
• Example: create an external JavaScript file that prints Hello Javatpoint in a
alert dialog box.
[Link]
<html> [Link]
<head> function msg() { alert("Hello PPSU");
<script type="text/javascript" src="[Link]"></script> </head> }
<body>
<p>Welcome to JavaScript</p>
<form> Output:
<input type="button" value="click" Hello PPSU
</form>
</body>
</html>
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 the code.
• There are two types of comments in JavaScript.
1. Single-line Comment
2. Multi-line Comment
</body>
</html>
3. Using [Link]()
• You can use an alert box to display data:
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<script>
[Link](5 + 6);
</script>
</body>
</html>
4. Using [Link]()
• For debugging purposes, you can call the [Link]() method in the
browser to display data.
<html>
<body>
<h2>Activate Debugging</h2>
<p>F12 on your keybord will activate debugging.</p>
<p>Then select "Console" in the debugger menu.</p>
<p>Then click Run again.</p>
<script>
[Link](5 + 6);
</script>
</body>
</html>
[Link] Print
• JavaScript does not have any print object or print methods.
• You cannot access output devices from JavaScript.
• The only exception is that you can call the [Link]() method in the browser to print
the content of the current window
• Example:
<html>
<body>
<button >Print this page</button>
</body>
</html>
Data Types
• One of the most fundamental characteristics of a programming language is the
set of data types it supports. These are the type of values that can be
represented and manipulated in a programming language.
• JavaScript allows you to work with three primitive data types:
JavaScript Variable
• Variables are containers for storing data (values).
• Declaring a variable tells Javascript that a variable of a given name exists so that the javascript
interpreter can understand references to that variable name throughout the rest of the script.
• A JavaScript variable is simply a name of storage location. There are two types of variables in
JavaScript : 1) local variable and 2) global variable.
Example:
1) x = 10;
2) var _value="sonoo";
3) let x = 10;
4) const PI = 3.141592653589793;
5) <script>
var x = 10;
var y = 20;
var z=x+y;
[Link](z);
</script>
5. JavaScript Var
<html> Output:
<body> Redeclaring a Variable Using var
<h2>Redeclaring a Variable Using var</h2>
2
<p id="demo"></p>
<script>
var x = 10;// Here x is 10
{
var x = 2;// Here x is 2
}
// Here x is 2
[Link]("demo").innerHTML = x;
</script>
</body>
</html>
4. JavaScript Let
• Variables defined with let cannot be Redeclared.
• Variables defined with let must be Declared before use.
• Variables defined with let have Block Scope.
<html>
<body>
Output:
<h2>Redeclaring a Variable Using let</h2> Redeclaring a Variable Using let
<p id="demo"></p>
<script> 10
let x = 10; // Here x is 10
{
let x = 2; // Here x is 2
}
// Here x is 10
[Link]("demo").innerHTML = x;
</script>
</body>
</html>
6. JavaScript Const
• Const is another keyword to declare a variable when you do not want to change
the value of that variable for the whole program.
• The difference is just that var is for normal variable declaration whose value can
be changed, whereas a variable value declared using const keyword cannot be
changed.
<html> Output:
<body> The value of const variable x = 16
<script>
const x = 16;
[Link]("The value of const variable x = " + x”);
</script>
</body>
</html>
1. JavaScript local variable
• A JavaScript local variable is declared inside block or function. It is accessible
within the function or block only.
• For example:
2. JavaScript global variable
• A JavaScript global variable is accessible from any function. A variable i.e.
declared outside the function or declared with window object is known as
global variable.
• For example:
3. Declaring JavaScript global variable within function
• To declare JavaScript global variables inside function, you need to use window
object.
• For example:
• Now it can be declared inside any function and can be accessed from any function.
For example:
<html> m();
<body> n();
<script>
function m(){ </script>
[Link]=100;//declaring global variable by window object </body>
} </html>
function n(){
alert([Link]);//accessing global variable from other function
}
When to Use var, let, or const?
[Link] declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed (Arrays and Objects)
4. Only use let if you can't use const
5. Only use var if you MUST support old browsers
2. Assignment Operators
3. Comparison Operators
4. String Operators
5. Logical Operators
6. Bitwise Operators
7. Ternary Operators
8. Type Operators
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. String Operators
• All the comparison operators above can also be used on strings:
let text1 = "A";
let text2 = "B";
let result = text1 < text2;
• strings are compared alphabetically
• The + can also be used to add (concatenate) strings
• The += assignment operator can also be used to add (concatenate) strings
let text1 = "What a very ";
text1 += "nice day";
[Link](text1)
5. Logical Operators
6. Type Operators
7. Bitwise Operators
• Bit operators work on 32 bits numbers.
• Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a
JavaScript number.
Strings
• A string can be defined as a sequence of letters, digits, punctuation and so on.
• Strings can be joined together with the + operator, which is called concatenation.
• For Example,
• mystring = “my college name is ” + “Darshan”;
• As string is an object type it also has some useful features.
• For Example,
• lenStr = [Link];
• Which returns the length of the string in integer
Strings (Cont.)
• There are also number of methods available for string.
Strings (Cont.)
• An escape sequence is a sequence of characters that does not represent itself when used
inside a character or string, but is translated into another character or a sequence of
characters that may be difficult or impossible to represent directly.
• Example : Code
function myFunction(p1, p2) {
return p1 * p2;
}
Functions
• When JavaScript reaches a return statement, the function will stop executing.
• If the function was invoked from a statement, JavaScript will "return" to execute the
code after the invoking statement.
• The code inside the function will execute when "something" invokes (calls) the
function:
• When an event occurs (when a user clicks a button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
• let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";
object={property1:value1,property2:value2.....propertyN:valueN}
2) By creating instance of Object
The syntax of creating object directly is given below:
var objectname=new Object();
Here, new keyword is used to create object.
3) By using an Object constructor
• Create function with arguments.
• Each argument value can be assigned in the current object by using this
keyword.
• The this keyword refers to the current object.
JavaScript’s inbuilt Objects
• JavaScript comes with some inbuilt objects which are,
• String
• Date
• Array
• Boolean
• Math
• RegExp
etc….
Math Object in JavaScript
• The Math object allows you to perform mathematical tasks.
• The Math object includes several mathematical constants and
methods.
• Example for using properties/methods of Math:
Code
<script>
var x=[Link];
var y=[Link](16);
</script>
Math Object in JavaScript
• Math object has some properties which are,
Math Object in JavaScript
• Math object has some properties which are,
Document Object Model
• The document object represents the whole html document.
[Link]("name")
[Link]() method
• The [Link]() method returns all the
element of specified tag name.
[Link]("name")
Browser Object Model
• The Browser Object Model (BOM) is used to interact with the
browser.
• The default object of browser is window means you can call all the
functions of window by specifying window or directly.
• For example:
[Link]("hello javatpoint");
is same as:
alert("hello javatpoint");
• You can use a lot of properties (other objects) defined underneath the
window object like document, history, screen, navigator, location,
innerHeight, innerWidth
Window Object
• The window object represents a window in browser. An object of window is
created automatically by the browser.
• Window is the object of browser, it is not the object of javascript. The
javascript objects are string, array, date etc.
• Methods of window object
Example of open() in javascript
Example of setTimeout() in javascript
• It performs its task after the given milliseconds.
JavaScript History Object
• The JavaScript history object represents an array of URLs visited by
the user. By using this object, you can load previous, forward or any
particular page.
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
Form events:
Event Performed Event Handler Description
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the
browser unloads it
resize onresize When the visitor resizes the window of the browser
Click Event Example
MouseOver Event
Focus Event
Keydown Event
Load event
JavaScript addEventListener()
• The addEventListener() method is used to attach an event handler to a
particular element. It does not override the existing event handlers.
• Events are said to be an essential part of the JavaScript.
• A web page responds according to the event that occurred.
• An event listener is a JavaScript's procedure that waits for the occurrence of an
event.
• The addEventListener() method is an inbuilt function of JavaScript.
• We can add multiple event handlers to a particular element without
overwriting the existing event handlers.
• Syntax
[Link](event, function, useCapture);
• parameters event and function are widely used. The third parameter is
optional to define. The values of this function are defined as follows.
• Parameter Values
• event: It is a required parameter. It can be defined as a string that specifies the
event's name.
• function: It is also a required parameter. It is a JavaScript function which
responds to the event occur.
• useCapture: It is an optional parameter. It is a Boolean type value that
specifies whether the event is executed in the bubbling or capturing phase. Its
possible values are true and false. When it is set to true, the event handler
executes in the capturing phase. When it is set to false, the handler executes in
the bubbling phase. Its default value is false.
Example of using the addEventListener() method.
We have to click the given HTML button to see the effect.
Adding Multiple events to the same element.
Form Validation
• It is important to validate the form submitted by the user because it
can have inappropriate values. So, validation is must to authenticate
user.
Accessing field value by document object
• [Link] is used to get the value of name field.
• Here, document is the root element that represents the html
document.
• form1 is the name of the form.
• name is the attribute name of the input text.
• value is the property, that returns the value of the input text.
Example 1: Validate the name and password. The name can’t be empty and
password can’t be less than 6 characters long.
• Example 2: Retype Password Validation
Example 3: Number Validation
In JavaScript NaN is short for "Not-a-Number". The isNaN() method returns true if a value
is NaN. The isNaN() method converts the value to a number before testing it.
Example 4:Email validation
[0-9]
3
It matches any decimal digit from 0 through 9.
[a-z]
4
It matches any character from lowercase a through lowercase z.
[A-Z]
5
It matches any character from uppercase A through uppercase Z.
[a-Z]
6
It matches any character from lowercase a through uppercase Z.
2. Quantifiers
The frequency or position of bracketed character sequences and single characters can be denoted by a special
character. Each special character has a specific connotation. The +, *, ?, and $ flags all follow a character
sequence.
[Link]. Expression & Description
p+
1
It matches any string containing one or more p's.
p*
2
It matches any string containing zero or more p's.
p?
3
It matches any string containing at most one p.
p{N}
4
It matches any string containing a sequence of N p's
p{2,3}
5
It matches any string containing a sequence of two or three p's.
p{2, }
6
It matches any string containing a sequence of at least two p's.
p$
7
It matches any string with p at the end of it.
^p
8
It matches any string with p at the beginning of it.
Examples
[Link]. Expression & Description
[^a-zA-Z]
1 It matches any string not containing any of the characters ranging
from a through z and A through Z.
^.{2}$
2
It matches any string containing exactly two characters.
<b>(.*)</b>
3
It matches any string enclosed within <b> and </b>.
p(hp)*
4 It matches any string containing a p followed by zero or more instances of the
sequence hp.
3. Literal characters
<script>
x = 10;
y = 15;
z = x + y;
[Link](z);
[Link](a);//a is not intialized
</script>
Debugger Keyword
• JavaScript provides debugger keyword to set the breakpoint through the code itself.
The debugger stops the execution of the program at the position it is applied. Now, we can
start the flow of execution manually.
• If an exception occurs, the execution will stop again on that particular line.
<script>
x = 10;
y = 15;
z = x + y;
debugger;
[Link](z);
[Link](a);
</script>
JavaScript Hoisting
• Hoisting is a mechanism in JavaScript that moves the declaration of variables and
functions at the top. So, in JavaScript we can use variables and functions before
declaring them.
<script>
x=10;
[Link](x);
var x;
</script>
JavaScript Function Hoisting
<script>
[Link](sum(10,20));
function sum(a,b)
{
return a+b;
}
</script>
JavaScript Strict Mode
• sometimes the JavaScript code displays the correct result even it has some
errors. To overcome this problem we can use the JavaScript strict mode.
• The JavaScript provides "use strict"; expression to enable the strict mode. If
there is any silent error or mistake in the code, it throws an error.
• The "use strict"; expression can only be placed as the first statement in a
script or in a function.
<script>
x=10;
[Link](x);
</script>
JavaScript Strict Mode
<script>
"use strict";
x=10;
[Link](x);
</script>
<script>
[Link](sum(10,20));
function sum(a,a)
{
"use strict";
return a+a;
}
</script>
jQuery JavaScript
It is a javascript library. It is a dynamic and interpreted web-development programming
language.
The user only need to write the required jQuery code The user needs to write the complete js code
There is no requirement for handling multi-browser Developers develop their own code for handling multi-browser
compatibility issues. compatibility.
It is required to include the URL of the jQuery library in theJavaScript is supportable on every browser. Any additional
header of the page. plugin need not to be included.
It depends on the JavaScript as it is a library of js. jQuery is a part of javascript. Thus, the js code may or may not
depend on jQuery.
It contains only a few lines of code. The code can be complicated, as well as long.
It is quite an easy, simple, and fast approach. It is a weakly typed programming approach.
jQuery is an optimized technique for web designing. JavaScript is one of the popular web designing programming
languages for developers that introduced jQuery.
jQuery creates DOM faster. JavaScript is slow in creating DOM.
jQuery
• A free and open-source javascript library which is basically used for designing,
traversing and manipulating the HTML DOM.
• A DOM is a tree-like structure used to represent the elements of a webpage.
• jQuery helps the designer to use javascript code easily for their websites.
• The advanced approach to jQuery enables to create powerful dynamic webpages
and web applications.
• The syntax of jQuery is designed to make things easy, such as:
1. Navigation of a document
2. Selection of DOM elements
3. Creating animations
4. Handling events
5. Developing Ajax applications.
Many of the biggest companies on the Web use jQuery, such as:
• Google
• Microsoft
• IBM
• Netflix
Adding jQuery library
• There are several ways to start using jQuery on your web site.
• You can:
• 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="[Link]"></script>
</head>
jQuery CDN
• If you don't want to download and host jQuery yourself, you can include
it from a CDN (Content Delivery Network).
• Google CDN:
• <head>
• <script
src="[Link]
ript>
• </head>
jQuery Syntax
• The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the
element(s).
• All selectors in jQuery start with the dollar sign and parentheses:
$().
jQuery Selector
Syntax Description
$("*") Selects all elements
$(this) Selects the current HTML element
$("[Link]") 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"
• $("p")
<!DOCTYPE html>
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>
The #id Selector The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.
<!DOCTYPE html>
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p id="test">This is another paragraph.</p>
<button>Click me</button>
</body>
</html>
The .class Selector The jQuery .class selector finds elements with a specific class.
<!DOCTYPE html>
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
</script>
</head>
<body>
<h2 class="test">This is a heading</h2>
<p class="test">This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>