Why Study JavaScript?
JavaScript is one of the 3 languages all web developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages
It is open and cross-platform.
Most popular programming language.
JavaScript helps you to develop front-end as well as back-end software
using different JavaScript based framework like jQuery,[Link] etc.
Lots of libraries already developed which can be used directly in your
software development to reduce time.
Application of JavaScript
Client-side validation
Manipulating HTML Pages
User Notification
Back-end Data Loading
Presentation
Server Application
What is JavaScript?
Dynamic computer programming Language.
Lightweight and most commonly used as a part of
webpage.
It is interpreted programming language with object
oriented capability.
JavaScript was first known as LiveScript but Netscape
changed its name to JavaScript.
Javascript is usually embedded directly into HTML pages.
Javascript is use for the css and html code.
It works in all major browsers, such as internet Explorer,
chrome, opera….etc
Use of JavaScript
JavaScript use to create dynamic webpages.
JavaScript use to create richer client-side interface of
webpage.
JavaScript can be use for security and validations.
Java script can be use to fetch user information like IP
address. Brower details Etc.
Advantage of JavaScript
Less server interaction.
Immediate feedback to user.
Richer interface.
Increase Interactivity
How to write JavaScript?
JavaScript Statement are placed within the <script>--
</script> html tag in webpage.
<script> tag normally kept within <head> Tag.
<script> tag alerts the browser program to start
interpret all text between these tag.
<script>
---------JavaScript code--------
</script>
Two Important Attribute
Language: This attribute you have to specify what type
of scripting language you are using.
Type: This attribute is indicates the scripting language
in use value should be set to text /javascript.
Comments in JavaScript
• <!---- comment in javascript //-- >
• //----single line comment.
• /*------*/----multiple line comment.
Example
<html>
<body>
<script language=“javascript” type=“text/javascript”>
<!-
[Link](“hello world!”)
//- >
</script>
</body>
<html>
White space and Line Break
Javascript ignores spaces,tabs an newlines that
appear in javascript program.
Semicolons are optional
• Javascript are generally followed by semicolon character.
• It allows you to omit this semicolon if each of your
statement are placed in a separate line.
Case Sensitive
• It is case sensitive language.
• time /=(notequal) TIME
<script language=“javascript” type=“text/javascript”>
<!—
Var1=10
Var2=30
//-->
</script>
<script language=“javascript” type=“text/javascript”>
<!—
Var1=1; Var2=30;
//-->
</script>
Where to place JavaScript?
To include javascript in an HTML file are as follow:
Script in <head>-------------</head> section.
Script in <body>-------------</body> section.
Script in external file and then include in <head>------</head>
section.
JavaScript in <head> Section.
If you have script that run on some event, such as when user click somewhere then you
will place that script in head section.
Example:
<html>
<head>
<script type = "text/javascript">
<!-- function sayHello()
{ alert("Hello World") } //-->
</script>
</head>
<body>
<input type = "button" value = "Say Hello" />
</body>
</html>
JavaScript in <body> Section
When script run as the page loads so that the script generates content in the page, then the script goes
in the <body> section of the document.
Example:
<html>
<head>---------------- </head>
<body>
<script type = "text/javascript">
<!–
[Link]("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
JavaScript in external file
The script tag provides a mechanism to allow you to store javascript in an
external file then include it into HTML file.
To use JavaScript from an external file source, you need to write all your
JavaScript source code in a simple text file with the extension ".js" and include
that file in head section.
Example:([Link])file
<html>
<head>
<script type = "text/javascript" src = "[Link]">----</script>
</head>
<body> ....... </body>
</html>
JavaScript Variable
What is variable?
How to define a variable?
Rules and instructions to choose variable name?
Print and use a variable?
Types of variable?
variable
Variables are “containers” for storing information.
JavaScript variables are used to hold values or expressions.
Rule:
Variable name are case sensitive.(y and Y are two different variable)
Variable names must begin with a letter or the underscore character.
Note: you declare JavaScript variables with the var keyword.
Syntax:
Var x; or var x=5;
Var abc; or var abc=“kinjal”;
Also assign values to the variables when you declare them.
When you assign a text value to a variable, use quotes around the
value.
Example:
<html>
<body>
<script type="text/javascript" >
var jeansp=1900; ,shirtp=1100;
total=jeansp+shirtp;
[Link]("<br>price of jeans = <b>"+jeansp+"</b><br> price of shirt
=<b>"+shirtp+"</b><br> total amount =<b>"+ total+"<br>");
</script>
</body>
</html>
Variable Types
[Link]:
it can only be accessed within that function
Local variables are destroyed when you exit the function.
[Link]:
It declare outside a function and all scripts and functions on the web
page can access it.
It destroyed when you close the page.
<head>
<script type="text/javascript" language="javascript">
var name=“kinjal"; //global
function hello()
{
//var name1=“palak"; //local
alert("my name is "+ name);
[Link]("my name is "+ name1);
}
function abc()
{
alert("hello "+ name);
}
[Link]("Hey "+name+" it is working...!!!");
[Link]("Hey "+name1+" it is working...!!!");
</script>
</head>
<body>
<input type="button" value="press me..!" > <input type="button" value="Click..!" ></body>
JavaScript Operator
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Arithmetic Operator
Addition: Add two Operand
Subtraction: subtract the second operand from the
first.
Multiplication: Multiply two Operand
Division: Divide the numerator by the denominator
Modulus: Output the remainder of an integer division.
Increment: Increases an Integer value by 1. +
+a=a+1;
Decrement: Decreases an integer value by 1. –b = b-1;
Comparison Operator
Equal(==):Checks if the value of two operands are equal or not, if yes, then
the condition becomes true.
Not Equal(!=):Checks if the value of two operands are equal or not, if the
values are not equal, then the condition becomes true.
Grater than(>):Checks if the value of the left operand is greater than the value
of the right operand, if yes, then the condition becomes true.
Less than(<):Checks if the value of the left operand is less than the value of
the right operand, if yes, then the condition becomes true.
Greater than or equal to(>=):Checks if the value of the left operand is greater
than or equal to the value of the right operand, if yes, then the condition
becomes true.
Less than or equal to(<=):Checks if the value of the left operand is less than
or equal to the value of the right operand, if yes, then the condition becomes
true.
Logical Operator
Logical AND(&&):If both the operands are non-zero, then the
condition becomes true.
Ex:(A && B) is true
Logical OR(||): If any of the two operands are non-zero, then the
condition becomes true.
Ex: (A || B) is true
Logical NOT(!): Reverses the logical state of its operand. If a
condition is true, then the Logical NOT operator will make it false.
Ex: ! (A && B) is false
Bitwise Operator
Bitwise AND (&): It performs a Boolean AND operation on each bit
of its integer arguments.
Bitwise OR( | ) : It performs a Boolean OR operation on each bit of
its integer arguments.
Bitwise XOR (^): It performs a Boolean exclusive OR operation on
each bit of its integer arguments. Exclusive OR means that either
operand one is true or operand two is true, but not both.
Bitwise Not (~): It is a unary operator and operates by reversing all
the bits in the operand.
Left Shift(<<): It moves all the bits in its first operand to the left
by the number of places specified in the second operand. New bits
are filled with zeros. Shifting a value left by one position is
equivalent to multiplying it by 2, shifting two positions is
equivalent to multiplying by 4, and so on.
Right Shift(>>):Binary Right Shift Operator. The left operand’s
value is moved right by the number of bits specified by the right
operand.
Assignment Operator
Simple Assignment(=) Assigns values from the right side operand to the left
side operand A-=A%B
Add and Assignment(+=):It adds the right operand to the left operand and
assigns the result to the left operand.
Subtract and Assignment(-=):It subtracts the right operand from the left
operand and assigns the result to the left operand.
Multiply and Assignment(*=): It multiplies the right operand with the left
operand and assigns the result to the left operand.
Divide and Assignment(/=):It divides the left operand with the right operand
and assigns the result to the left operand.
Modules and Assignment(%=) It takes modulus using two operands and
assigns the result to the left operand.
JavaScript Conditional Statement
JavaScript Supports conditional statement which are
used to perform different actions based on different
condition.
If –else
Switch Case
While Loop
For Loop
For…in
If-else statement
JavaScript Supports the following
If. Else statement—
• If statement
• If Else statement
• If. Else if… statement
If Statement
The if statement is the fundamental control statement
that allows JavaScript to make decision and execute
statement.
Syntax:
if (expression)
{
Statement to be executed if expression is true
}
Example
<html>
<body>
<script type = "text/javascript">
<!-- var age = 20;
if( age > 18 )
{
[Link]("<b>Qualifies for driving</b>");
} //-->
</script>
</body>
</html>
If…else statement
if…else statement…if the resulting value is true, the
given statement in the if block are executed. If the
expression is false then the given statement in the else
block are executed.
Syntax:
if (expression)
{ Statement(s) to be executed if expression is true }
else
{ Statement(s) to be executed if expression is false }
Example
<html>
<body>
<script type = "text/javascript">
<!-- var age = 20;
if( age > 18 )
{
[Link]("<b>Qualifies for driving</b>");
}
Else
{
[Link]("<b>Does not qualify for driving</b>");
}
</script>
</body>
</html>
if...else if... statement
In this statement if is part of the else clause of the previous
statement. Statements are executed based on the true condition, if
none of the condition is true, then else block Is executed.
Syntax:
if (expression 1)
{ Statement(s) to be executed if expression 1 is true }
else if (expression 2)
{ Statement(s) to be executed if expression 2 is true }
else if (expression 3)
{ Statement(s) to be executed if expression 3 is true }
Else
{ Statement(s) to be executed if no expression is true }
Example
<html>
<body>
<script type = "text/javascript">
<!-- var book = "maths";
if( book == "history" )
{ [Link]("<b>History Book</b>"); }
else if( book == "maths" )
{ [Link]("<b>Maths Book</b>"); }
else if( book == "economics" )
{ [Link]("<b>Economics Book</b>"); }
else
{ [Link]("<b>Unknown Book</b>"); } //-->
</script>
</body>
<html>
JavaScript Switch Case
• The objective of a switch statement is to
give an expression to evaluate and several
different statements to execute based on the
value of the expression.
• The interpreter checks each case against
the value of the expression until a match is
found.
• If nothing matches, a default condition
will be used.
Syntax:
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break; ...
case condition n: statement(s)
break;
default: statement(s)
}
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
[Link]("demo").innerHTML = "Today is " + day;
</script>
</body>
</html>
While Loop
The purpose of a while loop is to execute a
statement or code block repeatedly as long as
an expression is true. Once the expression
becomes false, the loop terminates.
Syntax:
while (expression)
{
Statement(s) to be executed if
expression is true
}
Example
<html>
<body>
<script type = "text/javascript">
<!-- var count = 0;
[Link]("Starting Loop ");
while (count < 10)
{
[Link]("Current Count : " + count + "<br />"); count++;
}
[Link]("Loop stopped!");
//-->
</script>
</body>
</html>
Do While Loop
The do...while loop is similar to the while loop
except that the condition check happens at the end
of the loop. This means that the loop will always
be executed at least once, even if the condition
is false.
Syntax:
Do
{
Statement(s) to be executed;
} while (expression);
Example
<html>
<body>
<script type = "text/javascript">
<!-- var count = 0;
[Link]("Starting Loop" + "<br />");
Do
{
[Link]("Current Count : " + count + "<br />"); count++;
}
while (count < 5);
[Link]("Loop stopped!"); //-->
</script>
</body>
</html>
For Loop
The 'for' loop is the most compact form of looping. It includes the following three important parts −
1. loop initialization where we initialize our counter to a starting value. The initialization statement is
executed before the loop begins.
2. test statement which will test if a given condition is true or not. If the condition is true, then the code
given inside the loop will be executed, otherwise the control will come out of the loop.
3. iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Syntax:
for (initialization; test condition; iteration statement)
{
Statement(s) to be executed if test condition is true
}
Example
<html>
<body>
<script type = "text/javascript">
<!-- var count;
[Link]("Starting Loop" + "<br />");
for(count = 0; count < 10; count++)
{
[Link]("Current Count : " + count ); [Link]("<br />");
}
[Link]("Loop stopped!"); //-->
</script
</body>
</html>
JavaScript Loop Control (Break)
The break statement, which was
briefly introduced with
the switch statement, is used to
exit a loop early, breaking out of
the enclosing curly braces.
Example
<html>
<body>
<script type = "text/javascript">
<!-- var x = 1;
[Link]("Entering the loop<br /> ");
while (x < 20)
{
if (x == 5)
{
break; // breaks out of loop completely
}
x = x + 1; [Link]( x + "<br />"); }
[Link]("Exiting the loop!<br /> "); //-->
</script>
</body>
</html>
continue
The continue statement tells the interpreter to immediately start the next iteration of the loop
and skip the remaining code block. When a continue statement is encountered, the program
flow moves to the loop check expression immediately and if the condition remains true, then
it starts the next iteration, otherwise the control comes out of the loop.
Example
<html>
<body>
<script type = "text/javascript">
<!-- var x = 1;
[Link]("Entering the loop<br /> ");
while (x < 10)
{ x = x + 1;
if (x == 5)
{ continue; // skip rest of the loop body }
[Link]( x + "<br />"); }
[Link]("Exiting the loop!<br /> "); //-->
</script>
</body>
</html>
JavaScript Function
A function is a group of reusable code which can be called
anywhere in your program.
Function eliminates the need of writing same code again
and again.
In JavaScript function is define using function keyword and
followed by a unique function name.
Syntax:
<script type = "text/javascript">
<!-- function functionname(parameter-list)
{ statements } //-->
</script>
Example
<html>
<head>
<script type = "text/javascript">
function sayHello()
{ [Link] ("Hello there!"); }
</script>
</head>
<body>
<form> <input type = "button" value = "Say Hello">
</form>
</body>
</html>
JavaScript DOM
DOM Represents the whole html content.
Document Object Model (DOM) is a platform and
language-neutral interface that allows programs and
scripts to dynamically access and update the content,
structure, and style of a document."
When html document is loaded in the browser, it
become a document object.
It is root element that represents html document and it
has various properties and methods.
With help of document object model we can add
dynamic content to the web pages.
Methods of DOM
Accessing field value by document object
<script type="text/javascript">
function abc(){
var name=[Link];
alert("Welcome: "+name+ “<br>”);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" value="print name"/>
</form>
[Link]() method
[Link]() method return the element of specified
id.
[Link]() method used to get value of the input
text and here we have to define if for input field.
<script type="text/javascript">
function square()
{
var number=[Link]("number").value;
alert(number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/>
<input type="button" value="cube" ></form>
[Link]()
The [Link]() method returns all the element of specified
name.
<script type="text/javascript">
function element()
{
var allgenders=[Link]("gender");
alert("Genders:"+[Link]);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
<input type="button" " value="Genders">
</form>
[Link]()method
The [Link]() method returns all the element
of specified tag name.
<script type="text/javascript">
function countp(){
var totalpara=[Link]("p");
alert("total p tags are: "+[Link]);
}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragrap</p>
<p>Let's see the simple example</p>
<button paragraph</button>
innerHTML Method
The innerHTML Method can be used to write the
dynamic html on the html document.
innerHTML Method Mostly used in web pages to
generate the dynamic html such as registration form,
comment form, links etc.
Cont.
<script type="text/javascript" >
function showcommentform() {
var data="Name:<input type='text' name='name'><br>
Comment:<br><textarea rows='5' cols='80'></textarea> <br>
<input type='submit' value='Post Comment'>";
[Link]('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" ><div id="mylocation"></div>
</form>
Form Object
Form Object in HTML DOM is used to represent the
HTML form element. This tag is used to set or get
properties of <form> tag.
This element can be accessed by using
getElementById() method.
Syntax: [Link](“Form id”);
Form Object Property
Form Object Method
JavaScript Date Object
The Date object is a datatype built into the JavaScript language.
Once a Date object is created, a number of methods allow you to operate on it. Most methods
simply allow you to get and set the year, month, day, hour, minute, second, and millisecond
fields of the object, using either local time or UTC (universal, or GMT) time.
Syntax:
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond])
Parameter Description
No Argument: With no arguments, the Date() constructor creates a
Date object set to the current date and time.
milliseconds − When one numeric argument is passed, it is taken as
the internal numeric representation of the date in milliseconds, as
returned by the getTime() method. For example, passing the
argument 5000 creates a date that represents five seconds past
midnight on 1/1/70.
datestring − When one string argument is passed, it is a string
representation of a date, in the format accepted by
the [Link]() method.
year − Integer value representing the year. For compatibility (in order to
avoid the Y2K problem), you should always specify the year in full; use
1998, rather than 98.
month − Integer value representing the month, beginning with 0 for
January to 11 for December.
date − Integer value representing the day of the month.
hour − Integer value representing the hour of the day (24-hour scale).
minute − Integer value representing the minute segment of a time
reading from (0-59)
second − Integer value representing the second segment of a time
reading.
millisecond − Integer value representing the millisecond segment of a
time reading.
JavaScript Get Date Method
UTC GetDate Method
JavaScript SetDate Method
JavaScript Math Object
The math object provides you properties and methods for
mathematical constants and functions. Unlike other global
objects, Math is not a constructor. All the properties and methods
of Math are static and can be called by using Math as an object
without creating it.
Syntax:
var pi_val = [Link];
var sine_val = [Link](30);
JavaScript Regular Expression Object
A regular expression is a sequence of characters that forms a search
pattern.
When you search for data in a text, you can use this search pattern to
describe what you are searching for.
A regular expression can be a single character, or a more complicated
pattern.
Regular expressions can be used to perform all types of text
search and text replace operations.
Syntax: /pattern/modifiers;
JavaScript Windows Object
The window object represents a window in browser.
An object of window is created automatically by the
browser.
Windows is the object of browser.