[go: up one dir, main page]

0% found this document useful (0 votes)
6 views21 pages

Module 5

The document provides an overview of JavaScript, detailing its features, usage within HTML documents, and programming fundamentals. Key aspects covered include JavaScript's object-based nature, dynamic typing, and the use of the SCRIPT element for embedding code in HTML. Additionally, it outlines programming concepts such as variables, operators, control flow statements, and event handling in web pages.

Uploaded by

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

Module 5

The document provides an overview of JavaScript, detailing its features, usage within HTML documents, and programming fundamentals. Key aspects covered include JavaScript's object-based nature, dynamic typing, and the use of the SCRIPT element for embedding code in HTML. Additionally, it outlines programming concepts such as variables, operators, control flow statements, and event handling in web pages.

Uploaded by

avengersarelike
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

MODULE 5

JavaScript: Features of JavaScript, JavaScript in HTML doc, Programming Fundamentals,


exploring functions, Events: HTML Forms, keyboard, objects in JavaScript, onclick event,
mouse events, reset events, onsubmit event.

Java script is a client and server-side object-based scripting language that is used to make
interactive web pages.
Features of JavaScript:
1. Imperative and structured: implies that javascript supports all the syntaxes of the
structured programming language C, such as if statement, loops and the switch
statements. Semicolon is not necessary to terminate a statement.
2. Dynamic text: JavaScript supports dynamic typing, which means the type of a
variable is defined according to the value stored in it.
It is an object-based scripting language, which provides some built-in objects, such as
strings, math and date objects.
3. Functional: it does not support classes, instead using classes, objects are created from
the constructor functions
4. Prototype-based: javascript is a Prototype-based language, which means java script
uses prototypes instead of classes for inheritance. There are several Built-in objects
that represent a constructor functions such as Array(), Date(), Number(), String()
5. Platform-independent: user can write script once and run it anywhere and anytime

JavaScript in HTML doc:


User can insert javascript code in an HTML document by using the SCRIPT element.
SCRIPT element contains five attributes:
1. Async: specifies whether the script should be executed asynchronously or not
2. Type: specifies the Multipurpose Internet Mail Extensions(MIME) types of script
3. Charset: specifies character encoding used in the script
4. Defer: specifies whether the browser can continue parsing the web page or not
5. Src : specifies URL of a file that contains the script
Ways of using SCRIPT element in a webpage in the following three ways:
1. Javascript in the HEAD element
2. In the BODY element
3. As an external script file

Javascript in the HEAD element


the script placed inside the HEAD element runs when you perform some action, such as click
a link or the submit button.
<HEAD>
<SCRIPT type=” text/javascript”>
Code here
</SCRIPT>
</HEAD>
Example :
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h2>Demo JavaScript in Head</h2>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>

Javascript is in the body element:


It runs when a webpage starts loading in a web browser.
<BODY>
<SCRIPT type=” text/javascript”>
Code here
</SCRIPT>
</BODY>

Example:
<!DOCTYPE html>
<html>
<body>
<h2>Demo JavaScript in Body</h2>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>

Javascript in an external file:


When the javascript is very lengthy and if it need to use by several web pages, javascript code
is stored in an external file using .js extension.
To link external javascript file src attribute of the SCRIPT element is used to access the
script file
<HEAD>
<SCRIPT src =URL of the external file>
</SCRIPT>
</HEAD>

Example :
<!DOCTYPE html>
<html>
<body>
<h2>Demo JavaScript in Body</h2>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script src="app.js"></script>
</body>
</html>

app.js:
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}

Programming fundamentals of javascript


 Javascript helps to create interactive web pages and embed javascript statements directly
in an HTML document.
 Javascript can retrieve data from a source, process it and display the output
 Programming fundamentals of javascript are as follows:
1. Lexical structure
2. Variables
3. Operators
4. Control flow statements
5. Popup boxes
1. Lexical structure
a. Character set
b. Case sensitivity
c. White spaces and line breaks
d. Comments
e. Literals
f. Identifiers
g. Reserved words
Character set: it is a set of characters reserved to write javascript programs. In American
Standard code of Information Interchange (ASCII) character set, there were 128 different
characters. 96 characters are available for use and 32 are reserved as control
characters.
Symbols Names
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\' Single quote
\" Double quote
\\ backslash
Case sensitivity: javascript is a case-sensitive language, which means that keyword, variable
names, function names and identifiers should be typed with a consistent casing of letters
Example: var Marks;
Var marks; both the variables are distinct from each other
White spaces and line breaks: the javascript interpreter ignores tabs, spaces, and newlines
that appear in a program, except strings and regular expressions.
Example:
Function a(){
Var i=1;
Var j=2;
}
0r
Function b(){Var I = 1;Var j = 2;} both the functions are same
Comments: it refers to the text or code in a program that is ignored at the time of executing
the program.
There are 2 Types: single comment- starts with // and ends with the end of the line.
Multiline comment-starts with /* and ends with */
Literals: it is a data value that represents a fixed value in a program
Types of literals:
1. Numerical literals- a numeric literal can be expressed in the decimal(0-9),
hexadecimal (0-9 and a-f and A-F)and octal format(0-7)
2. Floating-point literals- decimal number can be positive or negative , a decimal point,
a fraction and an exponent
3. Boolean literal- it is used to make a decision in relational expression. There are two
values TRUE or FALSE
4. String literal- it can be a zero or more characters enclosed in double(“) or single (‘)
quotation mark.
Example: char ch=“a” or char ch=‘a’
Unicode Representation: We can specify char literals in Unicode representation ‘\
uxxxx’. Here xxxx represents 4 hexadecimal numbers.
char ch = '\u0061';// Here /u0061 represent a.
Escape Sequence: Every escape character can be specified as char literals.
char ch = '\n';
5. Array literal- it is a list of zero or more expressions representing array elements that
are enclosed in square brackets [].
Var std=[“ajay”, “arun”, “anjali”];
6. Regular expression literal-it is also known as RegExp, is a pattern used to match a
character or string in some text.
Var myregexp=new RegExp(“abc”);
7. Object literal- it is collection of name value pairs enclosed in curly braces {}
Var games={cricket:11, carrom:4};

Identifiers: it refers to the names given to all the components, such as variables, and
methods, of a javascript program. Rules and guidelines for identifiers as follows
 Identifiers must starts with a letter, dollar sign($), or underscore(_)
 It cannot start with a number.
 It can contain any combination of letters, a dollar sign, and numbers after the first
character.
 It can be any length.
 Identifiers are case-sensitive.
 It cannot contain reserved words or keywords.
Reserved words: these are the words whose meanings are already defined to the javascript
interpreter.

2. Variables: in javascript, data can be temporarily stored in a variables, which are the
named locations in the memory.
Syntax: var is KEYWORD and variable_name represents the name of the variables
Example: Var variable_name; or
Var var1, var2; or
Var var=value
{ Var vname; vname=value;}
3. Operators: Operators are used to perform operations on variables and values.
Operators work on one or more operands i.e, an operator can take the values of more
than one operand.
List of operators:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Conditional operators

Arithmetic operators

Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x–y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x

Assignment operators it used to assign values to variables.

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x–3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Comparison operators

 Comparison operators are used to compare two values (or variables).


 It helps us to find answers and make decisions. The return value of a comparison is
either true or false. These values are known as Boolean values

Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Logical operators

 user can also test for true or false values with logical operators.
 Logical operators are used to determine the logic between variables or values:

Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)

conditional operators

?: -- it returns the second operand if the first operand is true. If the first operand is false, it
returns the third operand

Example---- a=1, b=2


Res=(a<b)?a:b;

A is less than b so it returns a

4. Control flow statements


java compiler executes the code from top to bottom. The statements in the code are
executed according to the order in which they appear. However, Java provides
statements that can be used to control the flow of Java code. Such statements are
called control flow statements.
These are the special statements that control or alter the sequence in which the script
statements are executed the decision regarding the execution of a statement is based
on the value

Javascript provides three types of control flow statements.

1. Selection statement – if, if else, switch


2. Loop statement- while, do while, for
3. Jump statement-break, continue

1. Selection statements
o if statements: It evaluates a Boolean expression and enables the program to
enter a block of code if the expression evaluates to true.

syntax of if statement is given below.

if(condition)
{
statement 1; //executes when condition is true.
}
Example :
let age=20;
if(age>=18){
console.log(“You are an adult”);
}

o if else

The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.

Syntax:
if(condition) {
statement 1; //executes when condition is true.
}
else{
statement 2; //executes when condition is false.
}

Example :
let age=16;
if(age>=18){
console.log(“You are an adult”);
}else{
console.log(“You are a minor”);
}
o switch statement

Switch statements are like if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the
variable which is being switched.

Syntax:

switch (expression) {

case value1:

// Code to execute if expression === value1

break;

case value2:

// Code to execute if expression === value2

break;

default:

// Code to execute if no cases match

Example :

let day = 3;

switch (day) {
case 1:

console.log("Monday");

break;

case 2:

console.log("Tuesday");

break;

case 3:

console.log("Wednesday");

break;

default:

console.log("Another day");

 The switch statement compares day to each case.


 If a match is found, the corresponding block executes, and the break statement
prevents further execution.

2. Loop statements
o While loop

The while loop is also used to iterate over the number of statements multiple times.

It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements
after the loop will be executed.

The syntax of the while loop is given below.

initialization

while(condition){

//looping statements
updation
}
Example :
let i=0;
while(i<=10)
{
console.log(i);
i++;
}

o do while loop

The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iterations is not known and we have to execute the loop at
least once, we can use do-while loop.

It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.

initialization
do{
//statements
updation
} while (condition);

Example :

let i=0;
do{
console.log(“The number is”,i);
i++;
}while(i<=10);

let i=0;
do{
console.log(“The number is”,i);
i++;
}while(i<=0);

o for loop

It enables us to initialize the loop variable, check the condition, and increment/decrement in a
single line of code. We use the for loop only when we exactly know the number of times, we
want to execute the block of code.

for(initialization;condition; increment/decrement) {
//block of statements
}
Example:
for (let i=0; i<5; i++){
console.log(“Hello World”,i);
}
3. Jump statements Jump statements are used to transfer the control of the program to
the specific statements.

There are two types of jump statements

o break statement: the break statement is used to break the current flow of the
program and transfer the control to the next statement outside a loop or switch
statement. However, it breaks only the inner loop in the case of the nested
loop.

We can use “break” statement either in for loop or while loop.

Example:

Using for loop :

for (let i=1; i<=5; i++)

if (i==3) {

break;

console.log(i);

Using while loop:

let i=1;

while(i<=5){

if(i==4)

break;
}

console.log(i);

i++;

o continue statement: the continue statement doesn't break the loop, whereas, it
skips the specific part of the loop and jumps to the next iteration of the loop
immediately.

Example :

for (let i=0; i<10; i++)

if (i==5){

continue;

document.write(i+”<br/>”);

5. Popup boxes:
popup boxes are used to display the message or notification to the user.
There are three types of pop-up boxes in JavaScript namely Alert Box, Confirm
Box and Prompt Box.
Alert Box: It is used when a warning message is needed to be produced. When the alert
box is displayed to the user, the user needs to press ok and proceed.
Syntax:
alert("your Alert here")
Example:
<!DOCTYPE html>
<html>
<head>
<title>Alert Box</title>
</head>
<body>
<center>
<h3>Alert Box</h3>
<button onclick="Alert()">Click here for alert box</button>
<!-- Alert box function -->
<script>
function Alert() {
alert("displays an alert message"+" and also error message");
}
</script>
</center>
</body>
</html>
Prompt Box: It is a type of pop up box which is used to get the user input for further use.
After entering the required details user must click ok to proceed next stage else by pressing
the cancel button user returns the null value.
Syntax:
prompt("your Prompt here")
Example:
<!DOCTYPE html>
<html>
<head>
<title>Prompt Box</title>
</head>
<body>
<h3>Prompt Box used to input a value from user</h3>
<input type="button" onclick="Prompt();" value="Click here for Prompt box"/>
<!-- Prompt box function -->
<script>
function Prompt() {
var x = prompt("Enter your mail here :");
document.write("Your ID : " + x);
}
</script>
</body>
</html>
Confirm Box: It is a type of pop-up box that is used to get authorization or permission
from the user. The user must press the ok or cancel button to proceed.
Syntax:
confirm("your query here")
Example:
<!DOCTYPE html>
<html>
<head>
<title>Pop-up Box type | Confirm Box</title>
</head>
<body>
<h3>Confirm Box is used to get authorization or permission from the user.</h3>
<button onclick="Confirm()">Click here for Confirm box</button>
<p id="a"></p>
<!-- Confirm box function -->
<script>
function Confirm() {
var x;
if (confirm("Press a button") == true)
{
x = "OK pressed";
} else {
x = "Cancel";
}
document.getElementById("a").innerHTML = x;
}
</script>
</body>
</html>
JAVASCRIPT FUNCTIONS

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

A JavaScript function is executed when "something" invokes it (calls it).

A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3)


{
// code to be executed
}

Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Function Invocation

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 Return

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.
Functions often compute a return value. The return value is "returned" back to the "caller":

Example

Calculate the product of two numbers, and return the result:

let x = myFunction(4, 3); //Function is called, return value will end up in x

function myFunction(a, b)
{
return a*b; //Function returns the product of a and b
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>

Function scope
A scope refers to an area which a function and its variables are accessible.
Two categories of scope of a function
1 Global- specifies that a function can be called or accessed from
anywhere in a program
2 Local- specifies that a function can be called or accessed only
within its parent function
Timing Events

The window object allows execution of code at specified time intervals.

These time intervals are called timing events.

The two key methods to use with JavaScript are:

 setTimeout(function, milliseconds)

Executes a function, after waiting a specified number of milliseconds.


Example :

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Timing</h2>

<p>Click "Try it". Wait 3 seconds. The page will alert "Hello".</p>

<p>Click "Stop" to prevent the first function to execute.</p>

<p>(You must click "Stop" before the 3 seconds are up.)</p>

<button onclick="myVar = setTimeout(myFunction, 3000)">Try it</button>

<button onclick="clearTimeout(myVar)">Stop it</button>

<script>

function myFunction() {

alert("Hello");

</script>

</body>

</html>

 setInterval(function, milliseconds)

Same as setTimeout(), but repeats the execution of the function continuously.

Example :

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Timing</h2>

<p>A script on this page starts this clock:</p>


<p id="demo"></p>

<script>

setInterval(myTimer, 5000);

function myTimer() {

const d = new Date();

document.getElementById("demo").innerHTML = d.toLocaleTimeString();

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

 The setTimeout() Method


 window.setTimeout(function, milliseconds);
 The window.setTimeout() method can be written without the window prefix.
 The first parameter is a function to be executed.
 The second parameter indicates the number of milliseconds before execution.
 The clearTimeout() method stops the execution of the function specified in
setTimeout().
 window.clearTimeout(timeoutVariable)
 The window.clearTimeout() method can be written without the window prefix.
 The clearTimeout() method uses the variable returned from setTimeout():
 myVar=setTimeout(function, milliseconds);
clearTimeout(myVar);

Objects in javascript:
 The JS language is based on objects. In JS we can create an object in two ways either
by creating a direct instance or by creating an object using a function template.
 A direct instance of an object is created by using the new keyword.
 Syntax: let Obj=new object();
 Properties and methods can be added to an object by using a period(.) followed by a
property or method name, as
Obj.name=”aaa”;
Obj.age=20;
Obj.getvalue();
All event objects in the HTML DOM are based on the Event Object.

Explanation :
Syntax :
let obj = new Object();
The new keyword can be used to create an instance of an object. This creates an empty
object in JavaScript using the built-in Object constructor.
Adding Properties and Methods:
You can use the dot (.) notation to add properties or methods to the object.
obj.name = "John";
obj.age = 25;
obj.getValue = function () {
return this.name + " is " + this.age + " years old.";
};
console.log(obj.getValue()); // Output: "John is 25 years old."

All event objects (like MouseEvent and KeyboardEvent) has access to the Event Object's
properties and methods.

Javascript objects

Event Description

onchange An HTML element has been changed

onclick The user clicks an HTML element

Onmouseover The user moves the mouse over an HTML element

onmouseout The user moves the mouse away from an HTML element

onkeydown The user pushes a keyboard key

onload The browser has finished loading the page

Keyboard Events

Event Occurs When

onkeydown A user presses a key

onkeypress A user presses a key


onkeyup A user releases a key

Mouse Events

Event Occurs When

onclick A user clicks on an element

oncontextmenu A user right-clicks on an element

ondblclick A user double-clicks on an element

onmousedown A mouse button is pressed over an element

onmouseenter The mouse pointer moves into an element

onmouseleave The mouse pointer moves out of an element

onmousemove The mouse pointer moves over an element

onmouseout The mouse pointer moves out of an element

onmouseover The mouse pointer moves onto an element

onmouseup A mouse button is released over an element

You might also like