You are on page 1of 65

Javascript

Javascript
• JavaScript is a programming language that executes
on the browser. It turns static HTML web pages into
interactive web pages by dynamically updating
content, validating form data, controlling
multimedia, animate images, and almost everything
else on the web pages. JavaScript is the third most
important web technology after HTML and CSS.
JavaScript can be used to create web and mobile
applications, build web servers, create games, etc.
• The HTML script tag <script> is used to embed data or
executable client side scripting language in an HTML
page. Mostly, JavaScript or JavaScript based API code
inside a <script></script> tag. An HTML page can
contain multiple <script> tags in
the <head> or <body> tag. The browser executes all
the script tags, starting from the first script tag from
the beginning.
Eg
<!DOCTYPE html> <html>
<body> <h1> JavaScript Working</h1>
<script>
alert('Hello, how are you?') </script>
</body> </html>
• Multiple script tags:>>
<!DOCTYPE html>

<html>
<head>
<title>JavaScript Demo</title>
<script>
alert('Executing JavaScript 1')
</script>
</head>
<body>
<h1> JavaScript </h1>

<script>
alert('Executing JavaScript 2')
</script>

<p>This page contains multiple script tags.</p>

<script>
alert('Executing JavaScript 3')
</script>
</body>
</html>
• External script file:
• A <script> tag can also be used to include an
external script file to an HTML web page by
using the src attribute.
• If we don't want to write inline JavaScript code
in the <script></script> tag, then you can also
write JavaScript code in a separate file
with .js extension and include it in a web page
using <script> tag and reference the file via src
attribute.
• syntax:>>
Case Sensitive>>JavaScript is a case-sensitive
scripting language. So, name of functions,
variables and keywords are case sensitive. For
example, myfunction and MyFunction are
different, Name is not equal to nAme, etc.
Variable>>In JavaScript, a variable is declared
with or without the var keyword .for declaring
variable we can also use “let”.
Semicolon>>JavaScript statements are separated
by a semicolon. However, it is not mandatory to
end a statement with a semicolon, but it is
recommended.
<script> var one = 1; two = 2; three = 3; //three
different statements
var four = 4; //single statement
var five = "Five" //single statement without ;
</script>
Code comment>>Write comment after double
slashes // or write multiple lines of comments
between /* and */
String>>A string is a text in JavaScript. The text
content must be enclosed in double or single
quotation marks.
<script> var msg = "Hello World" //JavaScript
string in double quotes
var msg = 'Hello World' //JavaScript string in
single quotes </script>
Numbers>>JavaScript allows you to work with
any type of number like integer, float,
hexadecimal etc.
keywords>> are reserved words in JavaScript,
which cannot be used as variable names or
function names.
Following are>>
JavaScript Message Boxes:
JavaScript provides built-in global functions to
display messages to users for different purposes,
e.g., displaying a simple message or displaying a
message and take the user's confirmation or
displaying a popup to take the user's input
value. they are:>>
• alert()
• confirm()
• prompt()
Alert Box

Use the alert() function to display a message to the user that requires their


attention. This alert box will have the OK button to close the alert box.
The alert() function takes a parameter of any type e.g., string, number,
Boolean etc. So, no need to convert a non-string type to a string type.eg>>
<!DOCTYPE html>
<html>
<body>
<h1>Demo: alert()</h1>

<script>
alert("This is an alert message box."); // display string message

alert('This is a number: ' + 100); // display result of a concatenation

alert(100); // display number

alert(Date()); // display current date


</script>
</body>
</html>
Confirm box
• Sometimes we need to take the user's
confirmation to proceed. For example, we want
to take the user's confirmation before saving
updated data or deleting existing data. In this
scenario, use the built-in function confirm().
• The confirm() function displays a popup message
to the user with two buttons, OK and Cancel.
The confirm() function returns true if a user has
clicked on the OK button or returns false if
clicked on the Cancel button. we can use the
return value to process further.
<!DOCTYPE html>
<html>
<body>
<h1> confirm()</h1>
<p id="msg"></p>

<script>
var data;

if (confirm("Do you want to save changes?") == true) {


data = "Data saved successfully!";
} else {
data = "Save Canceled!";
}

document.getElementById("msg").innerHTML = data;

</script>
</body>
</html>
Prompt Box
• Sometimes we may need to take the user's input to
do further actions. For example, you want to
calculate EMI based on the user's preferred tenure
of the loan. For this kind of scenario, use the built-in
function prompt().
• The prompt() function takes two string parameters.
The first parameter is the message to be displayed,
and the second parameter is the default value which
will be in input text when the message is displayed.
<!DOCTYPE html>
<html>
<body>
<h1> prompt()</h1>
<p id="msg"></p>

<script>
var tenure = prompt("Please enter preferred tenure in
years", "15");

document.getElementById("msg").innerHTML = "You have


entered " + tenure + " years";
</script>
</body>
</html>
****The alert(), confirm(),
and prompt() functions are global functions. So,
they can be called using the window object
e.g. window.alert(), window.confirm(),
and window.prompt().
Variables:>>
JavaScript is a loosely typed language. It means
it does not require a data type to be declared.
We can assign any literal values to a variable,
e.g., string, integer, float, Boolean, etc.
1. Variable stores data value that can be changed later on.
2. Variables can be defined using var keyword or let. Variables
defined without var keyword become global variables.
3. Variables must be initialized before accessing it.
4. JavaScript allows multiple white spaces and line breaks in a
variable declaration.
5. Multiple variables can be defined in a single line separated by a
comma.
6. JavaScript is a loosely-typed language, so a variable can store
any type value.
7. Variable names are case-sensitive.
8. Variable names can contain letters, digits, or the symbols $ and
_. It cannot start with a digit 0 - 9.
9. Variables can have local or global scope. Local variables cannot
be accessed out of the function where they are declared,
whereas the global variables can be accessed from anywhere.
var new = 1; // numeric value
new = 'one'; // string value
new = 1.1; // decimal value
new = true; // Boolean value
new = null; // null value
Javascript Operators

• 1. Arithmetic Operators: arithmatic operations


• var x = 5, y = 10; var z = x + y; //performs
addition and returns 15
• z = y - x; //performs subtraction and returns 5
z = x * y; //performs multiplication and returns
50
• z = y / x; //performs division and returns 2
• z = x % 2; //returns division remainder 1
Unary operator
var x = 5;
• x++; //post-increment, x will be 5 here and 6
in the next line
• ++x; //pre-increment, x will be 7 here
• x--; //post-decrement, x will be 7 here and 6 in
the next line
• --x; //pre-decrement, x will be 5 here
<html>
<body>
<h1>Demo: JavaScript ++ and -- Operators</h1>
<p>x = 5;</p>
<p id="p1">x++=</p>
<p id="p2">x=</p>
<p id="p3">++x=</p>
<p id="p4">x--=</p>
<p id="p5">x=</p>
<p id="p6">--x=</p>

<script>
var x = 5;

document.getElementById("p1").innerHTML += x++; //post increment


document.getElementById("p2").innerHTML += x; // value changes here

document.getElementById("p3").innerHTML += ++x; //pre increment & value changes here

document.getElementById("p4").innerHTML += x--; //post decrement


document.getElementById("p5").innerHTML += x; //value changes here

document.getElementById("p6").innerHTML += --x; //pre decrement and value changes here

</script>
</body>
</html>
String Concatenation

• The + operator performs concatenation


operation when one of the operands is of string
type. The following example demonstrates
string concatenation even if one of the operands
is a string.eg
var a = 5, b = "Hello ", c = "World!", d = 10; a +
b; //returns "5Hello “
b + c; //returns "Hello World!“
a + d; //returns 15
b + true; //returns "Hello true"
c - b; //returns NaN; - operator can only used with
numbers
Comparison operator
• var a = 5, b = 10, c = "5";
• var x = a;
• a == c; // returns true
• a === c; // returns false
• a == x; // returns true
• a != b; // returns true
• a > b; // returns false
• a < b; // returns true
• a >= b; // returns false
• a <= b; // returns true
Logical operator
var a = 5, b = 10;
(a != b) && (a < b); // returns true
(a > b) || (a == b); // returns false
(a < b) || (a == b); // returns true
!(a < b); // returns false
!(a > b); // returns true
Assignment operator
<!DOCTYPE html>
<html>
<body>
<h1>Example: JavaScript Assignment Operators</h1>

<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<p id="p6"></p>

<script>
var x = 5, y = 10;

x = y;
document.getElementById("p1").innerHTML = x;

x += 1;
document.getElementById("p2").innerHTML = x;

x -= 1;
document.getElementById("p3").innerHTML = x;

x *= 5;
document.getElementById("p4").innerHTML = x;

x /= 5;
document.getElementById("p5").innerHTML = x;

x %= 2;
document.getElementById("p6").innerHTML = x;

</script>
</body>
</html>
Ternary operator
• The ternary operator starts with conditional
expression followed by the ? operator. The
second part (after ? and before :) will be
executed if the condition turns out to be true.
Suppose, the condition returns false, then the
third part (after :) will be executed.
• Eg>>
• var a = 10, b = 5; var c = a > b? a : b; // value of c
would be 10
• var d = a > b? b : a; // value of d would be 5
The getElementById Method
• The most common way to access an HTML
element is to use the id of the element.
• The easiest way to get the content of an
element is by using the innerHTML property.
• The innerHTML property is useful for getting
or replacing the content of HTML elements.
JavaScript if else Condition
JavaScript includes if-else conditional statements
to control the program flow, similar to other
programming languages.
JavaScript includes following forms of if-else
conditions:
1. if condition
2. if-else condition
3. else if condition
If condition:>>based on some condition
<!DOCTYPE html>
<html>
<body>
<h1> if condition execution</h1>

<script>
if( 1 > 0)
{
alert("1 is greater than 0");
}

if( 1 < 0)
{
alert("1 is less than 0");
}
</script>
</body>
</html>
If-else condition
• <!DOCTYPE html>
• <html>
• <body>
• <h1> if-else condition</h1>

• <script>
• var mySal = 500;
• var yourSal = 1000;

• if( mySal > yourSal)


• {
• alert("My Salary is greater than your salary");
• }
• else
• {
• alert("My Salary is less than or equal to your salary");
• }

• </script>
• </body>
• </html>
Else-if condition
• <!DOCTYPE html>
• <html>
• <body>
• <h1> if-else condition</h1>

• <script>
• var mySal = 500;
• var yourSal = 1000;

• if( mySal > yourSal)


• {
• alert("My Salary is greater than your salary");
• }
• else if(mySal < yourSal)
• {
• alert("My Salary is less than your salary");
• }

• </script>
• </body>
• </html>
JavaScript switch
• The switch is a conditional statement like if statement. Switch is useful when we want to execute one of the multiple code blocks
based on the return value of specified
<!DOCTYPE html>
<html>
<body>
<h1>switch </h1>

<script>
var str = "riya";

switch (str)
{
case "rohan":
alert("This is rohan");
case "riya":
alert("This is riya");
break;
case "rimty":
alert("This is rimty");
break;
default:
alert("Unknown Person");
break;
}
</script>
</body>
</html>
for loops
JavaScript for loop is used to execute code
repeatedly.
• for loop includes three parts: initialization,
condition and iteration. e.g.for(initializer;
condition; iteration){ ... }
• The code block can be wrapped with { } brackets.
• An initializer can be specified before starting for
loop. The condition and increment statements
can be included inside the block.
For loop
The for loop requires following three parts.
Initializer: Initialize a counter variable to start
with
Condition: specify a condition that must
evaluate to true for next iteration
Iteration: increase or decrease counter
<!DOCTYPE html>
<html>
<body>
<h1> for loop</h1>
<p id="p0"></p>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>

<script>
for (var i = 0; i < 5; i++)
{
document.getElementById("p" + i).innerHTML = i;
}
</script>
</body>
</html>
While loop
• JavaScript includes while loop to execute code
repeatedly till it satisfies a specified condition. Unlike
for loop, while loop only requires condition expression.
• Syntax>>
while(condition expression)
{
/* code to be executed till the specified condition is true
*/
}
<!DOCTYPE html>
<html>
<body>
<h1> while loop</h1>
<p id="p0"></p>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>

<script>
var i =0;

while(i < 5)
{
document.getElementById("p"
+i).innerHTML = i;
i++;
}
</script>
</body>
</html>
do while

• JavaScript includes another way of while loop,


that is do-while loop. The do-while loop is
similar to while loop the only difference is it
evaluates condition expression after the
execution of code block. So do-while loop will
execute the code block at least once.
Do
{ //code to be executed
}
while(condition expression)
<!DOCTYPE html>
<html>
<body>
<h1> do while loop</h1>
<p id="p0"></p>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>

<script>
var i =0;

do{

document.getElementById("p" + i).innerHTML = i;

i++;

} while(i < 5)

</script>
</body>
</html>
Functions

• JavaScript provides functions similar to most of the


scripting and programming languages.
• In JavaScript, a function allows us to define a block
of code, give it a name and then execute it as
many times as you want.
• A JavaScript function can be defined
using function keyword.
• Syntax:
//defining a function function <function-name>()
{ // code to be executed
};
//calling a function <function-name>();
example
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript function</h1>

<script>
function ShowMessage() {
alert(“this is done by function");
}

ShowMessage();
</script>
</body>
</html>
Function parameters
A function can have one or more parameters, which will be supplied by the calling code and can be
used inside a function. JavaScript is a dynamic type scripting language, so a function parameter can
have value of any data type.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript function parameters</h1>

<script>
function ShowMessage(firstName, lastName) {
alert("Hello " + firstName + " " + lastName);
}

ShowMessage("priyansh", "setia");
ShowMessage("sonali", "Garg");
ShowMessage(100, 200);

</script>
</body>
</html>
• JavaScript Objects
• JavaScript objects are written with curly braces.
• Object properties are written as name:value pairs, separated by commas.

Example:
<!DOCTYPE html>
<html>
<body>
<p id=“abc"></p>
<script>
document.getElementById(“abc").innerHTML =
typeof "Rahul" + "<br>" +
typeof 3.14 + "<br>" +
typeof false + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof {name:‘Rahul', age:34};
</script>
</body>
</html>
• The typeof Operator
• You can use the JavaScript typeof operator to find the type of a JavaScript
variable:

Example:
<!DOCTYPE html>
<html>
<body>
<p id=“abc"></p>
<script>
document.getElementById(“abc").innerHTML =
typeof "Rahul" + "<br>" +
typeof 3.14 + "<br>" +
typeof false + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof {name:‘Rahul', age:34};
</script>
</body>
</html>
Events in JavaScript

JavaScript's interaction with HTML is handled through events that occur when the user or
the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an
event. Other examples include events like pressing any key, closing a window, resizing a
window, etc.

onclick Event

This is the most frequently used event type which occurs when a user clicks the left button
of his mouse. You can put your validation, warning etc., against this event type.
Example

<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">

function abc() {
alert("Welcome to the School of CSE")
}

</script>
</head>
<body>
<form>
<input type="button" onclick="abc()" value="Test" />
</form>

</body>
</html>
onsubmit Event
onsubmit is an event that occurs when you try to submit a form. You can put your form
validation against this event type.

Example

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

function validate() {
alert("Validated");
}
</script>
</head>
<body>
<form method="POST" onsubmit="return validate()">
<input type="submit" value="Submit" >
</form>
</body>
</html>
onmouseover and onmouseout Events

These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and
the onmouseout triggers when you move your mouse out from that element.

Example:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function over() {
document.write ("Mouse Over Content will alter");
}
</script>
</head>
<body>
<div onmouseover="over()">
Hello LPU
</div>
</body>
</html>
Example

<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">

function out() {
document.write ("Mouse Out");
}
</script>
</head>
<body>
<div onmouseout="out()">
Hello LPU
</div>
</body>
</html>
onkeypress Event

The onkeypress event occurs when the user presses a key (on the keyboard).

Example

<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">

function abc() {
document.write ("Pressed");
}
</script>
</head>
<body>
<input type="text" onkeypress="abc()">
</body>
</html>
onload Event

The onload event occurs when an object has been loaded.


onload is most often used within the <body> element to execute a script once a web
page has completely loaded all content (including images, script files, CSS files, etc.).
Example

<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">

function abc() {
document.write ("Example of Text on Page Loading");
}
</script>
</head>
<body onload="abc()">
</body>
</html>
onreset Event

When you reset the form, a function is triggered which alerts some text

<!DOCTYPE html>
<html>
<body>
<form onreset= “abc()">
Enter name: <input type="text">
<input type="reset">
</form>

<script>
function abc()
{
alert("The form was reset");
}
</script>
</body>
</html>
JavaScript Form Validation

Form validation normally used to occur at the server, after the client had entered all
the necessary data and then pressed the Submit button.

If the data entered by a client was incorrect or was simply missing, the server would
have to send all the data back to the client and request that the form be resubmitted
with correct information. This was really a lengthy process which used to put a lot of
burden on the server.

JavaScript provides a way to validate form's data on the client's computer before
sending it to the web server. 
Example1: Matching Password and Confirm Password
 
<script type="text/javascript">
function CanSubmit() {
//alert("ok");
var pwd = document.forms[0].txtPassword.value
var cpwd = document.forms[0].txtConfirmPassword.value
if (pwd == cpwd)
return true;
else {
alert("Please make sure that Password and Confirm Password are Same");
return false;
}
}
</script>

<form action="" method="post" onsubmit ="return CanSubmit()">


Password: <input type="password" name="txtPassword" value="" /> <br />
ConfirmPassword: <input type="password" name="txtConfirmPassword" value="" />
<br />
<input type="submit" name="btnSubmit" value="Submit" />
</form>
Example 2: Providing alert before data will be deleted
 <script>
function CanDelete()
{
return confirm("Are you Sure to delete your Data");
}
</script> 
<input type="submit" name="btnDelete" value="Delete" onclick ="return CanDelete()" />
NUMERIC INPUT VALIDATE
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Validation</h2>
<p>Please input a number between 1 and 10:</p>
<input id="numb">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
// Get the value of the input field with id="numb"
let x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
let text;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script></body></html>
Example 3 Denominator cant be zero

function CheckDenominator() {
var SN = document.forms[1].txtSN.value;
if (SN == 0) {

alert("Denominator cant be zero");


return false;
}
else
return true;
}
 
<input type="submit" name="btnDel" value="/" onclick="return CheckDenominator()"/>
Example 4 Whether the values entered in texboxes are numbers are not?

function ValidateMathFunction()
{
var FN = document.forms[1].txtFN.value;
var SN = document.forms[1].txtSN.value;
if (FN == "" || SN == ""|| isNaN(FN)||isNaN(SN)) {
alert("Please ensure that valid data is inserted in both textboxes");
return false;
}
else
return true;
}
 
Example 5 Validating Email using Regular Expressions

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validateEmail()
{
var emailTextBox = document.getElementById("txtEmail");
var email = emailTextBox.value;
var emailRegEx = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-
9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

emailTextBox.style.color = "white";
if (emailRegEx.test(email))
{
emailTextBox.style.backgroundColor = "green";
}
else
{
emailTextBox.style.backgroundColor = "red";
}
}
</script>

</head>
<body>
Email : <input type="text" id="txtEmail" onkeyup="validateEmail()" />

</body>
</html>
JavaScript Timing Events

In JavaScript a piece of code can be executed at specified time interval. For example, you
can call a specific JavaScript function every 1 second. This concept in JavaScript is called
timing events. 

The global window object has the following 2 methods that allow us to execute a piece of
JavaScript code at specified time intervals.

setInterval(func, delay) - Executes a specified function, repeatedly at specified time


interval. This method has 2 parameters. The func parameter specifies the name of the
function to execute. The delay parameter specifies the time in milliseconds to wait before
calling the specified function.

setTimeout(func, delay) - Executes a specified function, after waiting a specified number


of milliseconds. This method has 2 parameters. The func parameter specifies the name of
the function to execute. The delay parameter specifies the time in milliseconds to wait
before calling the specified function. The actual wait time (delay) may be longer.
 
The following code displays current date and time in the div tag.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function getCurrentDateTime()
{
document.getElementById("timeDiv").innerHTML = new Date();
}

</script>
</head>
<body>
<div id="timeDiv" ></div>
<input type="submit" onclick="getCurrentDateTime()">
</body>
</html>
At the moment the time is static.
To make the time on the page dynamic, modify the script as shown below. Notice that the
time is now updated every second. In this example, we are using setInterval() method and
calling getCurrentDateTime() function every 1000 milli-seconds.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
setInterval(getCurrentDateTime, 1000);

function getCurrentDateTime()
{
document.getElementById("timeDiv").innerHTML = new Date();
}
</script>
</head>
<body>
<div id="timeDiv" ></div>
</body>
</html>
Starting and stopping the clock with button click : In this example, setInterval()method
returns the intervalId which is then passed to clearInterval() method. When you click
the "Start Clock" button the clock is updated with new time every second, and when you
click "Stop Clock" button it stops the clock.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var intervalId;

function startClock()
{
intervalId = setInterval(getCurrentDateTime, 1000);
}

function stopClock()
{
clearInterval(intervalId);
}
function getCurrentDateTime()
{
document.getElementById("timeDiv").innerHTML= new Date();
}
</script>
</head>
<body>
<div id="timeDiv" ></div> <br />
<input type="button" value="Start Clock" onclick="startClock()" />
<input type="button" value="Stop Clock" onclick="stopClock()" />
</body>
</html>

You might also like