Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Chapter 3 Web Technology II Javascript

The document discusses client-side and server-side scripting. Client-side scripting includes languages like JavaScript, jQuery and CSS that run in the browser. Server-side scripting includes languages like PHP, ASP.NET and Python that run on the server. The document also provides an introduction to JavaScript, discussing its uses, advantages, disadvantages and syntax. Key JavaScript concepts covered include variables, comments, and case sensitivity.

Uploaded by

maharjanprabhat5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Chapter 3 Web Technology II Javascript

The document discusses client-side and server-side scripting. Client-side scripting includes languages like JavaScript, jQuery and CSS that run in the browser. Server-side scripting includes languages like PHP, ASP.NET and Python that run on the server. The document also provides an introduction to JavaScript, discussing its uses, advantages, disadvantages and syntax. Key JavaScript concepts covered include variables, comments, and case sensitivity.

Uploaded by

maharjanprabhat5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 97

WEB TECHNOLOGY II

Chapter 3
INTRODUCTION
• Web Technology refers to the various tools and techniques that are utilized in
the process of communication between different types of devices over the
internet.
• A web browser is used to access web pages. Web browsers can be defined
as programs that display text, data, pictures, animation, and video on the
Internet.
• The three core languages that make up the World Wide Web are HTML, CSS,
and JavaScript. In the IT world, the internet is an essential platform, whether
it`s for developing or for consumer use. When developing a website, typically
three main languages come into play. These languages are JavaScript, CSS,
and HTML.
CLIENT SIDE SCRIPTING
• Client-side scripting languages create the scripts that run on the client side
(i.e. your browser). These are sent from the server by server-side scripts. Some
good examples are JavaScript, jQuery, CSS etc.
• Works at the front end and script are visible among the users.
• Does not need interaction with the server for processing.
• HTML, CSS, JavaScript, etc. languages involved.
• Can reduce the load to the server.
• Insecure
SERVER SIDE SCRIPTING
• Server-side scripting is a method of designing websites so that the process or
user request is run on the originating server. Server-side scripts provide an
interface to the user and limit access to proprietary data and help keep
control of the script source code.
• Works in the back end which could not be visible at the client end.
• Requires server interaction for processing.
• PHP, ASP.net, Ruby on Rails, ColdFusion, Python, etcetera. Languages
involved.
• Could effectively customize the web pages and provide dynamic websites.
• Relatively secure.
CLIENT SIDE SCRIPTING VS SERVER
SIDE SCIPTING

Assignment : Write the difference between client side scripting and server side scripting.
INTERNET TECHNOLOGY
• Internet is a global communication system that links together thousands of
individual networks. It allows exchange of information between two or more
computers on a network. Thus internet helps in transfer of messages through
mail, chat, video & audio conference, etc.
• Internet Technologies is a technical field that covers the necessary skills to
develop applications on the Internet or Internet based systems, harnessing e-
commerce, cloud, mobile, and Web based technologies.
INTRODUCTION TO JAVASCRIPT
• JavaScript is a cross-platform, object-oriented scripting language used to
make webpages interactive (e.g., having complex animations, clickable
buttons, popup menus, etc.). There are also more advanced server side
versions of JavaScript such as Node.
• Features
• JavaScript is a light weight, interpreted programming languaae.
• Complementary to and integrated with Java.
• Complementary to and integrated with HTML.
• Open and cross-platform
INTRODUCTION TO JAVASCRIPT
• Advantages
• Java script has less server interaction.
• It provide immediate feedback to the visitors.
• It provides the increased interactivity.
• You can use JavaScript to give rich interface to your visitors.
• Disadvantages
• Client-side JavaScript does not allow the reading or writing of files. This has kept
for security reasons.
• JavaScript cannot be used for networking applications because there is no such
support available.
• JavaScript doesn’t have any multi-threading or multiprocessor capabilities.
INTRODUCTION TO JAVASCRIPT
• Uses
• Client side validation.
• Dynamic drop down menus.
• Displaying date and time.
• Displaying pop-up windows and dialog boxes.
• Displaying clock.
JAVA SCRIPT FUNDAMENTAL

Positioning of script inside HTML document:


• The <script> element can be placed in the <head>, or <body> section of an
HTML document.
• But ideally, scripts should be placed at the end of the body section, just
before the closing </body> tag.
• It will make the pages load faster, since it prevents obstruction of initial page
rendering.
• Each <script> tag blocks the page rendering process until it has fully
downloaded and executed the JavaScript code.
• So placing them in the head section (i.e. <head> element) of the document
without any valid reason will significantly impact the website performance.
JAVASCRIPT SYNTAX
• A java script consist of JavaScript statement that are placed within the
<script> </script> HTML tag in a web page or within the external JavaScript
file having .js extension.
• At its simplest, JavaScript code consists series of statements and semicolon.
• For example:
• alert(‘Say hi’);
• Console.log(‘This’ + name + ’is rubbish’);
• For example;
<!DOCTYPE html>
<html>
<head>
<title> Example of JavaScript Statements </title> Output:
</head> 15
<body>
<script>
var x=5;
var y=10;
var sum=x+y;
document.write(sum); //Prints variable value
</script>
</body>
</html>
CASE SENSITIVITY IN JAVASCRIPT
• JavaScript code is case sensitive.
• This means that variables, language keywords, function names, and other
identifiers must always be typed with a consistent of letters.
• For example, the variable myVar must be typed myVar not MyVar or myvar.
• Similarly, the method name getElementById() must be typed with the exact
case not as getElementByID().
ADDING JAVA SCRIPT TO HTML
PAGE
• Java script can either be embedded directly inside the HTML page or
placed in an external script file and referenced inside the HTML page.
• Both methods use the <script> element.
• And third one is placing the java script code directly inside an HTML tag.
EMBEDDING JAVASCRIPT
• To embed java script in an HTML file, just add the code as the content of a <script>
element.
• The JavaScript code is for displaying string in the web page.
<! DOCTYPE html> Output:
<html lang=“en”> Hello World!
<head>
<title> Embedding Java Script </title>
</head>
<body>
<script>
document.write(“Hello World”);
</script>
</body>
</html>
CALLING EXTERNAL JAVA SCRIPT FILE
• We can place the JavaScript code into a separate file (with a .js extension), and call the
file in the HTML document through the src attribute of the <script> tag.
• It saves from representing the same task over the web site.
• For example:
<! DOCTYPE html>
<html lang=“en”>
<head>
<title> Linking External Java Script </title>
</head>
<body>
<div id=“greet”> </div>
<script src=“/examples/js/hello.js”></script>
</body>
</html>
PLACING THE JAVA SCRIPT CODE INLINE
• It can also place Java Script code inline by inserting it directly inside the HTML tag using
the special tag attributes such as onclick, onmouseover, onkeypress, onload etc.
• It should avoid placing large amount of Java Script code inline. But it makes the
JavaScript code difficult to maintain.
• For example:
Output:
<!DOCTYPE html>
<html>
Click Me
<head>
<title> Inlining JavaScript </title>
</head>
<body>
<button onclick = “alert(‘Hello World!)”> Click Me </button>
</body>
</html>
JAVA SCRIPT COMMENTS
• JavaScript comments can be used to explain JavaScript code, and to make it more
readable.
• JavaScript comments can also be used to prevent execution, when testing
alternative code.
Single Line Comments
• Single line comments start with //.
• Any text between // and the end of the line will be ignored by JavaScript (will not be
executed).
Example:
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
MULTI-LINE COMMENTS

• Multi-line comments start with /* and end with */.


• Any text between /* and */ will be ignored by JavaScript.
For example:
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
KEYWORDS
• JavaScript
keywords are
Keyword Description
reserved words.
Reserved words var Declares a variable
cannot be used as let Declares a block variable
names for variables. const Declares a block constant
if Marks a block of statements to be executed on a condition

switch Marks a block of statements to be executed in different cases

for Marks a block of statements to be executed in a loop

function Declares a function


return Exits a function
try Implements error handling to a block of statements
KEYWORDS
abstract else instanceof switch
boolean enum int synchronized

break export interface this


byte extends long throw
case false native throws
catch final new transient
char finally null true
class float package try
const for private typeof
continue function protected var
debugger goto public void
default if return volatile
delete implements short while
JAVASCRIPT VARIABLES
• Variables are containers for storing data (storing data values).
• 3 Ways to Declare a JavaScript Variable:
• Using var
• Used to declare variable globally.
• Syntax: var variableName=“variable_value”;
• Using let
• Used to declare variable locally.
• Syntax: let variableName=“variable_value”;
• Using const
• Used to declare variable locally but value are not changeable.
• Syntax: const varialeName=“variable_value”;

Note: We can declare multiple at one line using comma (,) operator.
example: var name=“Ram Sita”, age=13, isMarried=false;
Example:
<script>
// using var keyword.
var name = "Ram";
var age = "18";
document.write(name + " is " + age + "year old." + "<br>");
//using let keyword

if (true) {
let address = "butwal";
document.write("address is " + address + "<br>");
}
document.write("address is" + address + "<br>"); //show error address is not defined
//using const keyword
const phoneNo = "9898475869";
document.write("phoneNo is" + phoneNo);
</script>
JAVASCRIPT VARIABLE NAMES
While naming your variables in JavaScript, keep the following rules in mind.

1. You should not use any of the JavaScript keywords as a variable name.

2. JavaScript variable names should not start with a numbers (0-9). For e.g. :
1address is invalid.

3. They must begin with a letter or an underscore(_) or dollar($) character. For


example, 123test is an invalid variable name but _123test is a valid one.

4. JavaScript variable names are case-sensitive. For example, Name and name
are two different variables.
GENERATING OUTPUT IN JAVA SCRIPT
a) Writing Output to Browser Console
We can easily output a message or write data to the browser console using the
console.log() method. It is very powerful method for generating detailed output.
For example:
<!DOCTYPE html>
<html>
<body>

<script>
console.log(5 + 6);
</script>

</body>
</html>
B) DISPLAYING OUTPUT IN ALERT
DIALOG BOXES
• We can also use alert dialog boxes to display the message or output data to the user.
An alert dialog box is created using the window.alert() method.
• You can skip the window keyword.
• For example:
Example with out window keyword.
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>
<h1>My First Web Page</h1>
<h1>My First Web Page</h1>
<p>My first paragraph.</p> <p>My first paragraph.</p>
<script>
window.alert(5 + 6); <script>
</script> alert(5 + 6);
</script>
</body>
</html> </body>
C) OUTPUT TO THE BROWSER WINDOW
• We can use the document.write() method to write the content to the
current document only while that document is being parsed.
• For example:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button type="button" onclick="document.write(5 + 6)">Try it</button>
</body>
</html>
D) INSERTING OUTPUT
INSIDE AN HTML ELEMENT
• We can also write or insert output inside an HTML element using the element’s innerHTML
property.
• However, before writing the output first we need to select the element using a method such
as getElementById().
• For example:
<!DOCTYPE html>
<html>
<body>
<h2>The innerHTML Property</h2>
<p id="demo" onclick="myFunction()">Click me to change my HTML content
(innerHTML).</p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "I have changed!";
}
</script>
</body>
</html>
JAVA SCRIPT DATA TYPES
• Data types basically specify what kind of data can be stored and
manipulated within a program.
• There are two types of data types in Java Script.
 Primitive Data Type
 Non-Primitive Data Type
PRIMITIVE DATA TYPES
• Primitive data types can hold only one value at a time.

Data Type Description


String represents a sequence of characters e.g., “good”
Number represents numeric values e.g., 785
Boolean represents Boolean value e.g., true or false
Undefined represents an undefined value e.g., undefined
Null represents null i.e., no value at all e.g., null
PRIMITIVE DATA TYPES
<!DOCTYPE html> //creating variables //creating variables
<html lang="en"> var i = 25; var ar;
var j = 80.5; var b="Hello World!";
<head> var k = 4.25e+6; //printing variable values
<title>Using the primitive var l = 4.25e-6; document.write(ar + "<br>");
datatypes</title> //printing varibales values document.write(b);
</head> document.write(i + "<br>"); </script>
document.write(j + "<br>");
<body> document.write(k + "<br>"); <h2> Null Datatype</h2>
Now we are going to use the data document.write(l + "<br>"); <script>
types.
</script> //creaing variables
<h1>String Datatype</h1>
var c=null;
<script> <h1> Boolean Data type</h1> //printing variable values
//creating variables <script> document.write(c);
var a = "Let's have a cup of //creating Variables
coffee"; </script>
var isReading = true;
var b = 'He said"Hello " and left';
var isSleeping = false;
//printing variables values
//Printing Variables values </body>
document.write(a + "<br>");
document.write(isReading + </html>
document.write(b + "<br>"); "<br>");
</script> document.write(isSleeping);
</script>
<h1>Number Datatype</h1>
<h2>Undefined Datatype</h2>
<script>
<script>
NON PRIMITIVES DATA TYPES
• Non-primitive data types can hold collections of values and more complex
entities.
Data Type Description
Object represents an instance through which we can access members
Array represents a group of similar values
RegExp represents a regular expressions.
NON PRIMITIVE DATA TYPES

<html> "color": "silver", </script>


"wheels": 4
<head> }; <h1> Regular Expression</h1>
<title>Non Primitive //Print variables in browser <script>
Datatypes</title> console re= new
</head> console.log(person); RegExp(/'ab+c'/); //means
re=/ab+c/
console.log(car);
<body> //RegExp() is a
</script> function/constructor which is
Example of Non-Primitive Data
types used to create an object re.
<h1>Array Datatypes</h1> n=/ab+/.test(re);
<h1>Object Datatypes</h1>
<script> // In this we are going to test
<script>
//Creating Arrays an expression ab+ exists in re or
//Creating Objects not.
var ages = [18,20 , 16, 24];
var emptyObject = {}; document.write(n); //prints
var cities = ["Kathmandu", ture
var person = { "name": "Butwal", "Pokhara"];
"Ram", "class": "12", "rollno":
"twelve" }; //Printing array values </script>
//For Better Reading document.write(ages[0] + </body>
"<br>");
var car = { </html>
document.write(cities[2] +
"modal": "Ecosport", "<br>");
JAVASCRIPT OPERATORS

There are different types of JavaScript operators:


1. Arithmetic Operators
2. Assignment Operators
3. String Operators
4. Logical Operators
5. Comparison Operators
6. Bitwise Operator
7. Special Operators
JAVASCRIPT ARITHMETIC OPERATORS

• Arithmetic Operators are used to perform arithmetic on numbers:


• Arithmetic Operators Example
let a = 3; Operator Description
let x = (100 + 50) * a;
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
JAVASCRIPT ASSIGNMENT OPERATORS
Assignment operators assign values to JavaScript variables.
The Addition Assignment Operator (+=) adds a value to a variable.

Assignment Operator Example Same As


let x = 10; = x=y x=y
x += 5;
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
STRING OPERATOR
• The + operator can also be used to add (concatenate) strings.

Example
let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
The result of text3 will be:
John Doe
JAVASCRIPT LOGICAL OPERATORS

Operator Description
&& logical and
|| logical or
! logical not
JAVASCRIPT COMPARISON OPERATORS
Operator Description

== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
?: ternary operator (conditional operator)
JAVASCRIPT 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.
• The examples above uses 4 bits unsigned examples. But JavaScript uses 32-
bit signed numbers.
Operator Description Example Same as Result Decimal

& AND 5&1 0101 & 0001 0001 1

| OR 5|1 0101 | 0001 0101 5

~ NOT ~5 ~0101 1010 10


^ XOR 5^1 0101 ^ 0001 0100 4

<< left shift 5 << 1 0101 << 1 1010 10


>> right shift 5 >> 1 0101 >> 1 0010 2
>>> unsigned right shift 5 >>> 1 0101 >>> 1 0010 2
JAVASCRIPT SPECIAL OPERATORS
Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object type
, Comma operator allows multiple expression to be evaluated as
single statement
new Creates an instance (object)
delete Delete Operator deletes a property from the object
in In Operator checks if object has the given property
CONTROL STATEMENT
Control structure actually controls the flow of execution of a program. Following
are the several control structure supported by JavaScript.
• if … else
• switch case
• do while loop
• while loop
• for loop
JAVA SCRIPT IF ELSE STATEMENT
• While writing a program, there may be a situation when you need to adopt
one out of a given set of paths. In such cases, you need to use conditional
statements that allow your program to make correct decisions and perform
right actions.
• JavaScript supports conditional statements which are used to perform
different actions based on different conditions. Here we will explain
the If..else statement.
• JavaScript supports the following forms of if..else statement −
• if statement

• if...else statement

• if...else if... statement.


IF
The if statement is the fundamental control statement that allows JavaScript to
make decisions and execute statements conditionally.
Syntax:
if (expression){
Statement(s) to be executed if expression is true
}
EXAMPLE

<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
IF...ELSE STATEMENT
• The 'if...else' statement is the next form of control statement that allows
JavaScript to execute statements in a more controlled way.

Syntax:
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
EXAMPLE
<html>
Output:
<body> Does not qualify for driving.
<script>
var age = 15;
if (age > 18) {
document.write("<b>Qualifies for driving</b>");
} else {
document.write("<b>Does not qualify for driving</b>");
}
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
IF...ELSE IF... STATEMENT
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a
correct decision out of several conditions.

Syntax:
The syntax of an if-else-if statement is as follows −

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
}
<html>
<body>
<script>
var book = "maths"; EXAMPLE
if (book == "history") {
document.write("<b>History Book</b>");
Output:
} else if (book == "maths") {
Maths Book
document.write("<b>Maths Book</b>");
} else if (book == "economics") { Set the variable to different value and
document.write("<b>Economics Book</b>"); then try...
} else {
document.write("<b>Unknown Book</b>");
}
</script>
<p>Set the variable to different value and then
try...</p>
</body>
<html>
SWITCH CASE
• The basic syntax of the 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:

<script>
var grade='A';
document.write("Entering switch block<br/>");
switch (grade) {
case 'A': document.write("Good job<br/>");
break;
case 'B': document.write("Pretty good<br/>");
break;
case 'C': document.write("Passed<br/>");
break;
case 'D': document.write("Not so good<br/>");
break;
case 'F': document.write("Failed<br/>");
break;
default: document.write("Unknown grade<br/>")
}
document.write("Exiting switch block");
</script>
LOOPING STATEMENTS
• 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.

• for loop
• for-in loop
• for-of loop
• while loop
• do-while loop
FOR LOOP
• The for loop is the most compact form of looping and includes the following
three important parts −

• The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.

• The test statement which will test if the given condition is true or not. If
condition is true then code given inside the loop will be executed otherwise
loop will come out.

• The iteration statement where you can increase or decrease your counter.
• Syntax:

for (initialization; test condition; iteration statement){


Statement(s) to be executed if test condition is true
}

Example:
for(count = 0; count < 10; count++){
document.write("Current Count : " + count );
document.write("<br/>");
}
Example: This will produce following result which is
similar to while loop −
<script>
var count; Starting Loop
Current Count : 0
document.write("Starting Loop" + "<br/>"); Current Count : 1
for (count = 0; count < 10; count++) { Current Count : 2
Current Count : 3
document.write("Current Count : " + Current Count : 4
count); Current Count : 5
Current Count : 6
document.write("<br/>"); Current Count : 7
} Current Count : 8
Current Count : 9
document.write("Loop stopped!"); Loop stopped!
</script>
FOR IN LOOP
• The JavaScript for in loop is used to iterate the properties of an object. We
will discuss about it later.
• Syntax:
for (key in object) {
// code block to be executed
}
Example: Output:
John
<script> Doe
const person = { fname: "John", lname: 25
"Doe", age: 25 };
for (let x in person) {

document.write(person[x]; +"<br>");
}
</script>
WHILE LOOP
The purpose of a while loop is to execute a statement or code block
repeatedly as long as expression is true. Once expression becomes false, the
loop will be exited.

Syntax:
Initialization;
while (expression){
Statement(s) to be executed if expression is true;
counter parts;
}
Example: This will produce following result −
<script> Starting Loop
var count = 0; Current Count : 0
Current Count : 1
document.write("Starting Loop" + "<br/>"); Current Count : 2
while (count < 10) { Current Count : 3
Current Count : 4
document.write("Current Count : " + Current Count : 5
count + "<br/>"); Current Count : 6
Current Count : 7
count++; Current Count : 8
} Current Count : 9
Loop stopped!
document.write("Loop stopped!");
</script>
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:
initialization;
do {
Statement(s) to be executed;
Counter parts;
} while (expression);
This will produce following result −

Example: Starting Loop


Current Count : 0
Loop stopped!
<script>
var count = 0;
document.write("Starting Loop" + "<br/>");
do {
document.write("Current Count : " + count + "<br/>");
count++;
} while (count < 0);
document.write("Loop stopped!");
</script>
FUNCTIONS
• JavaScript functions are used to perform operations. We can call JavaScript
function many times to reuse the code.
• Advantage of JavaScript function
• There are mainly two advantages of JavaScript functions.
• Code reusability: We can call a function several times so it save coding.
• Less coding: It makes our program compact. We don’t need to write many lines
of code each time to perform a common task.
FUNCTION DEFINITION
• Before we use a function, we need to define it. The most common way to
define a function in JavaScript is by using the function keyword, followed by
a unique function name, a list of parameters (that might be empty), and a
statement block surrounded by curly braces.
• The syntax of declaring function is given below.

function functionName([arg1, arg2, ...argN]){


//code to be executed
}
• JavaScript Functions can have 0 or more arguments.
JAVA SCRIPT FUNCTION EXAMPLE

• Let’s see the simple example of function in JavaScript that does not has
arguments.

<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>

hello! this is message


JAVASCRIPT FUNCTION ARGUMENTS
• We can call function by passing arguments. Let’s see the example of function that
has one argument.

<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>

64
FUNCTION WITH RETURN VALUE
• We can call function that returns a value and use it in our program. Let’s see the
example of function that returns value.
<script>
function getInfo(){
return "hello javascript! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
OBJECT BASED PROGRAMMING WITH
JAVA SCRIPT AND EVENT HANDLING
• Object Based Programming with Java Script

• A JavaScript object is an entity having state and behavior (properties and


method). For example: car, pen, bike, chair, glass, keyboard, monitor etc.

• Properties can hold values of primitive data types and methods are functions.

• An object is a standalone entity because there is no class in javascript. However,


we can achieve class like functionality using functions.

• An Object can be created within curly braces ({}) with an optimal list of
properties.
CREATING OBJECTS IN JAVASCRIPT

There are 2 ways to create objects.


• By object literal
• By using an object constructor (using new keyword)
JAVASCRIPT OBJECT BY OBJECT LITERAL
• It is a simple way of creating an object using curly braces ({}) having number of
properties separated with comma and object delimited with semicolon(;).
• The syntax of creating object using object literal is given below:
• object={property1:value1,property2:value2.....propertyN:valueN}
• As you can see, property and value is separated by : (colon).
• Let’s see the simple example of creating object in JavaScript.

//object with no properties or methods


var emptyObject={};

//object with single property


var person={firstName:“Ram”};
JAVASCRIPT OBJECT BY OBJECT LITERAL
//object with single method
var message={
showMessage:function(val)
{
alert(val);
}
};
//object with properties and method
var person={
firstName:“Ram”,
lastName:“Sita”,
age:18,
getFullName:function()
{
return this.firstName+’’+this.lastName;
}
};
BY USING AN OBJECT CONSTRUCTOR
• The second way to create an object is with Object Constructor using new keyword.

• Here we can attach properties and methods using dot notation. Optionally, we can
also create properties using [] brackets and specifying property name as string.
• Syntax:
var objectName=new Object();
• The example of creating object by object constructor is given below.
BY USING AN OBJECT CONSTRUCTOR
• The example of creating object by object //by dot notation
constructor is given below. document.write(person.firstname + " ");
<script>
document.write(person.lastName + " ");
//creating object constructor using new document.write("Age is" + " " + person.age);
keyword.
document.write("<br>");
var person = new Object();
document.write(person.getFullName());
//Attach properties and methods to person
object document.write("<br>");
person.firstname = "Ram"; //by bracket notation
person["lastName"] = "Sita"; document.write(person["firstname"] + " ");
person.age = 18; document.write(person["lastName"] + " ");
person.getFullName = function () { document.write(person["age"] + "yearold");
return this.firstname + '' + this.lastName; </script>
};
//accessing properties and methods
LOOPING THROUGH OBJECT’S PROPERTIES
• It can iterate through the key value pairs of object using the for in loop. This loop is specially
optimized for iterating over object’s properties.
• Example:
<script>
var person={
name:”Prapti”,
age:12,
gender:”Female”
};
// Iterating over object properties
for(var i in person)
{
document.write(person[i]+””); //Prints: Prapti 12 Female
}
</script>
EVENT HANDLING WITH JAVA SCRIPT
• The change in the state of an object is known as an Event. In 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.
SOME OF THE HTML EVENTS AND
THEIR EVENT HANDLERS ARE:
Mouse events:
Event Event Handler Description
Performed
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.


EXAMPLE
Click Event:
<body>
<script>
function clickevent()
{
document.write("This is Javascript click event response.");
}
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
MOUSEOVER EVENT EXAMPLE
<body>
<script>
function mouseoverevent()
{
alert("This is JavaScript mouse over event response.);
}
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
Keyboard events:

Event Performed Event Handler Description


Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
KEYDOWN EVENT
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
</script>
Form events
Event Event Handler Description
Performed
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
FOCUS EVENT
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
function focusevent()
{
document.getElementById("input1").style.background=" red";
}
</script>
</body>
Window/Document events
Event Event Handler Description
Performed
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
LOAD EVENT

<body onload="window.alert('Page successfully loaded');">


<script>
document.write("The page is loaded successfully");
</script>
</body>
IMAGE OBJECT
• The Image object represents an HTML <img> element.

• Access an Image Object


You can access an <img> element by using getElementById():

• Example:
var x = document.getElementById("myImg");
CREATE AN IMAGE OBJECT
• You can create an <img> element by using the document.createElement()
method:

• Example:
var x = document.createElement("IMG");
EXAMPLE OF IMAGE OBJECT
<body> var x
<p> Click the button to create an IMG =document.createElement(“IMG”);
element. x.setAttribute(“src”,”rk3.gif”);
</p> x.setAttribute(“width”,”304”);
<button onclick=“myFunction()”> x.setAttribute(“height”,”304”);
Try it x.setAttribute(“alt”,”the image cannot
</button> access now, sorry for inconvenience.”);
<script> documet.body.appendChild(x);
function myFunction() }
{ </script>
</body>
IMAGE OBJECT PROPERTIES
Property Description
align Not supported in HTML5. Use style.cssFloat instead.
Sets or returns the value of the align attribute of an image
alt Sets or returns the value of the alt attribute of an image
border Not supported in HTML5. Use style.border instead.
Sets or returns the value of the border attribute of an
image
width Sets or returns the value of the width attribute of an image
height Sets or returns the value of the height attribute of an
image
naturalHeight Returns the original height of an image
naturalWidth Returns the original width of an image
src Sets or returns the value of the src attribute of an image
FORM OBJECT
• The Form object represents an HTML <form> element.
• You can create a <form> element by using the document.createElement()
method:
• Example:
var x = document.createElement("FORM");
• You can access a <form> element by using getElementById():
• Example:
var x = document.getElementById("myForm");

Form Object Collections


Collection Description
elements Returns a collection of all elements in a form
METHODS OF JAVASCRIPT
• Other than action and methods, there are the following useful methods also
which are provided by the HTML Form Element

• submit (): The method is used to submit the form.


• reset (): The method is used to reset the form values.
• handleEvent(): The handleEvent() method of form object is used to start or
invoke a form’s event handler for a specified event.
EXAMPLE
<script>
function CreateForm() {
var f = document.createElement("FORM");
document.body.appendChild(f);
var i = document.createElement("INPUT");
i.setAttribute("type", "password");
f.appendChild(i);
}
</script>
</head>
<body>
<h1>Form object example</h1>
<p>Create a FORM element containing an input element by
clicking the below button</p>
<button onclick="CreateForm()">CREATE</button>
<br><br>
</body>
CLIENT SIDE DATA VALIDATION
• When you enter data, the browser and/or the web server will check to see
that the data is in the correct format and within the constraints set by the
application. Validation done in the browser is called client-side validation.
• Client-side validation is visible to the user. It involves having validation on
input forms through JavaScript.
• For example, if the input is submitted for a phone number or email, a
JavaScript validator would provide an error if anything is submitted that does
not conform to a phone number or email.
FORM VALIDATION WITH
JAVASCRIPT
• It is important to validate the form submitted by the user because it can
have inappropriate values. So, validation is must to authenticate user.

• JavaScript provides facility to validate the form on the client-side so data


processing will be faster than server-side validation. Most of the web
developers prefer JavaScript form validation.

• Through JavaScript, we can validate name, password, email, date, mobile


numbers and more fields.
<body>
<script> Note: Similarly we can
function validateform(){ perform other types of
var name=document.myform.name.value; validation also.
var password=document.myform.password.value;

if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<form name="myform" method="post" action="abc.jsp" onsubmit="return validatefo
rm()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
JQUERY
• It is a lightweight, fast, small and feature rich JavaScript Library.
• It makes it much easier to code JavaScript on your website.
• It reduces the development time-consume, easy to add animation and
event handling programs.
• jQuery is a JavaScript framework that makes it easier to program for the
browser.
• jQuery library contains HTML/DOM manipulation, CSS manipulation, effects
and animation etc.
WHY JQUERY?
• Reasons to use jQuery are:
• Easy to understand.
• Easily integrated with other IDE.
• Faster.
• Animation becomes easy.
• SEO friendly.
• Run in all major browsers.
ASSIGNMENT
• Prepare notes and write question answer.

You might also like