[Go to site: main page, start]

0% found this document useful (0 votes)
9 views175 pages

Unit-4 JavaScript & JQuery

JavaScript is a versatile programming language primarily used for client-side scripting in web development, enabling dynamic and responsive web pages. It allows for various functionalities such as modifying HTML content, validating user input, and creating cookies, while also having advantages like speed and simplicity, but facing challenges with security and browser compatibility. The document covers JavaScript's structure, data types, variable declarations, operators, functions, conditional statements, and loops, providing examples and best practices for usage.

Uploaded by

zarana.gajjar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views175 pages

Unit-4 JavaScript & JQuery

JavaScript is a versatile programming language primarily used for client-side scripting in web development, enabling dynamic and responsive web pages. It allows for various functionalities such as modifying HTML content, validating user input, and creating cookies, while also having advantages like speed and simplicity, but facing challenges with security and browser compatibility. The document covers JavaScript's structure, data types, variable declarations, operators, functions, conditional statements, and loops, providing examples and best practices for usage.

Uploaded by

zarana.gajjar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript

• 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 scripts are almost written in the Javascript language to control


browser’s actions.

• 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

Single Line Comment Multi Line Comment


JavaScript Output
JavaScript can "display" data in different ways:
1. Writing into an HTML element, using innerHTML.
• To access an HTML element, JavaScript can use, the [Link](id)
method.
• The id attribute defines the HTML element. The innerHTML property defines the
HTML content .
2. Writing into the HTML output using [Link]().
• Using [Link]() after an HTML document is loaded, will delete all existing
HTML
3. Writing into an alert box, using [Link]().
• You can use an alert box to display data
4. Writing into the browser console, using [Link]().
• For debugging purposes, you can call the [Link]() method in the browser to
display data.
1. Using innerHTML
• To access an HTML element, JavaScript can use the
[Link](id) method.
• The id attribute defines the HTML element. The innerHTML property
defines the HTML content:
<html>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
2. Using [Link]()
• For testing purposes, it is convenient to use [Link]():
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<p>Never call [Link] after the document has finished loading.
It will overwrite the whole document.</p>
<script>
[Link](5 + 6);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h2>My First Web Page</h2>


<p>My first paragraph.</p>

<button type="button" + 6)">Try it</button>

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

• Difference Between var, let and const


Operator
1. Arithmetic Operators

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.

• A string in a JavaScript is wrapped with single or double quotes

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

• Some Useful Escape sequences :


Functions
• A JavaScript function is a block of code designed to perform a particular task.

• A JavaScript function is executed when "something" invokes it.

• A JavaScript function is defined with the function keyword, followed by a name,


followed by parentheses ().

• The parentheses may include parameter names separated by commas: (parameter1,


parameter2, ...)

• The code to be executed, by the function, is placed inside curly brackets.

• 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 value = toCelsius(77);


Functions Used as Variable Values
• Functions can be used the same way as you use variables, in all types of formulas,
assignments, and calculations.

• let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";

• let text = "The temperature is " + toCelsius(77) + " Celsius";


Example
Javascript Conditional Statements
• In JavaScript we have the following conditional statements:
• Use if to specify a block of code to be executed, if a specified condition is true
• Use else to specify a block of code to be executed, if the same condition is false
• Use else if to specify a new condition to test, if the first condition is false
• Use switch to specify many alternative blocks of code to be executed
[Link] Satement
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
if(expression){
//content to be evaluated
}
Example:
<html>
<body>
<script>
var a=20;
if(a>10){
[Link]("value of a is greater than 10");
}
</script>
</body>
</html>
2. IF…ELSE Satement
It evaluates the content whether condition is true of false. The syntax of JavaScript if-else statement is
given below.
if(expression){
//content to be evaluated if condition is true Example:
} <html>
<body>
else{
<script>
//content to be evaluated if condition is false var a=20;
} if(a%2==0){
[Link]("a is even number");
}
else{
[Link]("a is odd number");
}
</script>
</body>
</html>
3. IF…ELSE IF Satement
It evaluates the content only if expression is true from several expressions. The signature of
JavaScript if else if statement is given below.
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
3. IF…ELSE IF Satement
Example:
<html>
<body>
<script>
var a=20;
if(a==10){
[Link]("a is equal to 10");
}
else if(a==15){
[Link]("a is equal to 15");
}
else if(a==20){
[Link]("a is equal to 20");
}
else{
[Link]("a is not equal to 10, 15 or 20");
}
</script>
</body>
</html>
JavaScript Loops
• The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops. It makes
the code compact. It is mostly used in array.
• There are four types of loops in JavaScript.
• 1. for loop
• 2. while loop
• 3. do-while loop
• 4. for-in loop
1. For loop
The JavaScript for loop iterates the elements for the fixed number of times. It should be used if number of iteration is
known. The syntax of for loop is given below.
for (initialization; condition; increment)
{
code to be executed
}
• Example:
<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
[Link](i + "<br/>")
}
</script>
</body>
</html>
2. While loop
• The JavaScript while loop iterates the elements for the infinite number of times. It should be used if number of iteration is not
known. The syntax of while loop is given below.
while (condition)
{
code to be executed
}
• Example:
<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=15)
{
[Link](i + "<br/>");
i++;
}
</script>
</body>
</html>
3. Do – while lopp
• The JavaScript do while loop iterates the elements for the infinite number of times like while loop. But, code is
executed at least once whether condition is true or false. The syntax of do while loop is given below.
do{
code to be executed
}while (condition);
• Example:
<html>
<body>
<script>
var i=21;
do{
[Link](i + "<br/>");
i++;
}while (i<=25);
</script>
</body>
</html>
Arrays
Pop up Boxes
• Popup boxes can be used to raise an alert, or to get confirmation on
any input or to have a kind of input from the users.
• JavaScript supports three types of popup boxes.
1. Alert box
2. Confirm box
3. Prompt box
1. Alert box
• An alert box is used if you want to make sure information comes
through to the user.
• When an alert box pops up, the user will have to click "OK" to
proceed.
• It can be used to display the result of validation.
Code
<html>
<head>
<title>Alert Box</title>
</head>
<body>
<script>
alert("Hello World");
</script>
</body>
</html>
2. Confirm Box
• A confirm box is used if you want the user to accept something.
• When a confirm box pops up, the user will have to click either "OK"
or "Cancel" to proceed, If the user clicks "OK", the box returns true. If
the user clicks "Cancel", the box returns false.
• Example :
Code
<script>
var a = confirm(“Are you sure??");
if(a==true) {
alert(“User Accepted”);
}
else {
alert(“User Cancled”);
}
</script>
3. Prompt Box
• A prompt box is used if you want the user to input a value.
• When a prompt box pops up, user have to click either "OK" or
"Cancel" to proceed, If the user clicks "OK" the box returns the input
value, If the user clicks "Cancel" the box returns null.
Code
<script>
var a = prompt(“Enter Name");
alert(“User Entered ” + a);
</script>
JavaScript Objects
• A javaScript object is an entity having state and behavior (properties
and method). For example: car, pen, bike, chair, glass, keyboard,
monitor etc.
• JavaScript is an object-based language. Everything is an object in
JavaScript.
Creating Objects in JavaScript
• There are 3 ways to create objects.
• By object literal
• By creating instance of Object directly (using new keyword)
• By using an object constructor (using new keyword)
1) JavaScript Object by object literal

The syntax of creating object using object literal is given below:

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.

• When html document is loaded in the browser, it becomes a


document object.

• It is the root element that represents the html document.

• It has properties and methods.

• By the help of document object, we can add dynamic content to our


web page.
Properties of document object
Methods of document object
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.
[Link]() method
• The [Link]() method returns the element of
specified id.
• In the previous example, we have
used [Link] to get the value of the input
value.
• Instead of this, we can use [Link]() method to
get value of the input text.
• But we need to define id for the input field.
[Link]() method
• The [Link]() method returns all the
element of specified name.

• The syntax of the getElementsByName() method is given below:

[Link]("name")
[Link]() method
• The [Link]() method returns all the
element of specified tag name.

• The syntax of the getElementsByTagName() method is given below:

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

• The history object is the window property, so it can be accessed by:


[Link]
Or,
history
Property of JavaScript history object
Methods of JavaScript history object
JavaScript Navigator Object
• The JavaScript navigator object is used for browser detection. It can
be used to get browser information such as appName,
appCodeName, userAgent etc.

• The navigator object is the window property, so it can be accessed by:


[Link]
Or,
navigator
Property of JavaScript navigator object
Methods of JavaScript navigator object
JavaScript Screen Object
• The JavaScript screen object holds information of browser screen. It
can be used to display screen width, height, colorDepth, pixelDepth
etc.
• The navigator object is the window property, so it can be accessed by:
[Link]
Or,
screen
Property of JavaScript Screen Object
JavaScript Events
• 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.
Mouse events:
Event Performed Event Handler Description

click onclick When mouse click on an element


mouseover onmouseover When the cursor of the mouse comes over the element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.


Keyboard events

Event Performed Event Handler Description

Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
Form events:
Event Performed Event Handler Description

focus onfocus When the user focuses on an element


submit onsubmit When the user submits the form
blur onblur When the focus is away from a form element
change onchange When the user modifies or changes the value of a form
element
Window/Document 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

Criteria that need to be follow to validate the email id such as:

• email id must contain the @ and . character


• There must be at least one character before and after the @.
• There must be at least two characters after . (dot).
• lastIndexOf(): This function helps you find where a specific piece of text
shows up for the last time in a string.
• indexOf(): This function is similar, but it finds where a specific piece of text
appears for the first time in a string.
• When checking email addresses in JavaScript, you can use these functions to
make sure the email has an “@” and a “.” in the right places. This is a basic
way to check if an email address looks like it’s in the right format.
<!DOCTYPE html>
<html>
<head>
<title>Email Validation Example</title>
</head>
<body>
<h2>Email Validation Example</h2>
<input type="text" id="email" placeholder="Enter your email">
<button Email</button>
</body>
</html>
// Function to validate the email address
function validateEmail() {
// Retrieve the value from the input field with id 'email'
var email = [Link]("email").value;
// Find the position of the '@' character
var atPosition = [Link]("@");
// Find the position of the last '.' character
var dotPosition = [Link](".");
// Check if the '@' is in a valid position, and if the last '.' is in a valid position
if (atPosition < 1 || dotPosition < atPosition + 2 || dotPosition + 2 >= [Link])
{
alert("Please enter a valid email address.");
} else
{
alert("Email address is valid.");
}
}
Form validation with Regular Expressions
• A regular expression is an object that describes a pattern of
characters.
1. Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a
range of characters.

[Link]. Expression & Description


[...]
1
Any one character between the brackets.
[^...]
2
Any one character not between the brackets.

[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

[Link]. Character & Description


Alphanumeric
1
Itself
\0
2
The NUL character (\u0000)
\t
3
Tab (\u0009
\n
4
Newline (\u000A)
\v
5
Vertical tab (\u000B)
\f
6
Form feed (\u000C)
\r
7
Carriage return (\u000D)
4. Metacharacters

• A metacharacter is simply an alphabetical character preceded by a backslash


that acts to give the combination a special meaning.
[Link]. Character & Description
.
1
a single character
\s
2
a whitespace character (space, tab, newline)
\S
3
non-whitespace character
\d
4
a digit (0-9)
\D
5
a non-digit
\w
6
a word character (a-z, A-Z, 0-9, _)
\W
7
a non-word character
[\b]
8
a literal backspace (special case).
[aeiou]
9
matches a single character in the given set
[^aeiou]
10
matches a single character outside the given set
Email Validation using Regular Expression
Some of basic checks are as follows:
• Presence of @ and . character
• Presence of at least one character before and after the @.
• Presence of at least two characters after . (dot).
/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/

Key components of the regex pattern:


^: Start of the string.
[a-zA-Z0-9._-]+: Match one or more alphanumeric characters, dots,
underscores, or hyphens for the username part.
@: Match the "@" symbol.
[a-zA-Z0-9.-]+: Match one or more alphanumeric characters, dots, or
hyphens for the domain name.
\.: Match a period (dot), which separates the domain name and top-level
domain (TLD).
[a-zA-Z]{2,4}: Match the TLD, consisting of 2 to 4 alphabetical characters.
$: End of the string.
JavaScript Error
Throw, and Try...Catch...Finally
• The try statement defines a code block to run (to try).

• The catch statement defines a code block to handle any error.

• The finally statement defines a code block to run regardless of the


result.

• The throw statement defines a custom error.


JavaScript catches adddlert as an error,
and executes the catch code to handle it.
This example examines input. If the value is wrong, an exception (err) is thrown.
The exception (err) is caught by the catch statement and a custom error message is displayed.
The finally statement lets you execute code, after try and catch, regardless of the result.
The Error Object
• JavaScript has a built in error object that provides error
information when an error occurs.

• The error object provides two useful properties: name and


message

• Error Object Properties


Error Name Values
• Six different values can be returned by the error name property:
Error Name Description
EvalError An error has occurred in the eval() function
RangeError A number "out of range" has occurred
ReferenceError An illegal reference has occurred
SyntaxError A syntax error has occurred
TypeError A type error has occurred
URIError An error in encodeURI() has occurred
SyntaxError
JavaScript Debugging
• when programming code contains errors, nothing will happen. There are no
error messages, and you will get no indications where to search for errors.

• Searching for (and fixing) errors in programming code is called code


debugging.

• All modern browsers have a built-in JavaScript debugger.

• To perform debugging, we can use any of the following approaches:


1. Using [Link]() method
2. Using debugger keyword
Using [Link]() method
• The [Link]() method displays the result in the console of the
browser. If there is any mistake in the code, it generates the error
message.

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

• JavaScript hoisting is applicable only for declaration not initialization. It is required


to initialize the variables and functions before using their values.

<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

It is less time-consuming. It is more time consuming as the whole script is written.

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:

1. Download the jQuery library from [Link]


2. Include jQuery from a CDN, like Google
Downloading jQuery
• There are two versions of jQuery available for downloading:
1. Production version - this is for your live website because it has been minified and
compressed
2. Development version - this is for testing and development (uncompressed and
readable code)

• Both versions can be downloaded from [Link].

• 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 is an example of someone who host jQuery:

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

• 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:
1. $(this).hide() - hides the current element.
2. $("p").hide() - hides all <p> elements.
3. $(".test").hide() - hides all elements with class="test".
4. $("#test").hide() - hides the element with id="test".
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.

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

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

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


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")
<!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>

You might also like