0% found this document useful (0 votes)
15 views

S4 S6 S7 S8 S9 - JavaScript

This document provides an introduction to JavaScript. It discusses that JavaScript allows web pages to be more dynamic and interactive by executing code on the client-side browser. It describes client-side scripting and why it is used, including for validations and user event functionality. The benefits of both client-side and server-side scripting are outlined. Basic JavaScript concepts like variables, data types, operators, and control statements are defined. The document also demonstrates how to include JavaScript in HTML using the <script> tag and shows simple JavaScript code examples.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

S4 S6 S7 S8 S9 - JavaScript

This document provides an introduction to JavaScript. It discusses that JavaScript allows web pages to be more dynamic and interactive by executing code on the client-side browser. It describes client-side scripting and why it is used, including for validations and user event functionality. The benefits of both client-side and server-side scripting are outlined. Basic JavaScript concepts like variables, data types, operators, and control statements are defined. The document also demonstrates how to include JavaScript in HTML using the <script> tag and shows simple JavaScript code examples.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Session4: Introduction to

Javascript
To make web pages more dynamic and interactive, and it provides the
programming foundation for the server-side scripting

1
Client-side scripting
• Web browsers execute client-side scripting. It is used when browsers
have all code. Source code is used to transfer from webserver to
user’s computer over the internet and run directly on browsers. It is
also used for validations and functionality for user events.

2
Why use client-side programming?
• client-side scripting (JavaScript) benefits:
• usability: can modify a page without having to post back to the server (faster
UI)
• efficiency: can make small, quick changes to page without waiting for server
• event-driven: can respond to user actions like clicks and key presses
• server-side scripting (PHP) benefits:
• security: has access to server's private data; client can't see source code
• compatibility: not subject to browser compatibility issues
• power: can write files, open connections to servers, connect to databases, ...

3
Client Side Scripting

4
What is Javascript?
• Created by Netscape
• Originally called LiveWire then LiveScript
• A client-side scripting language
• Client-side refers to the fact that it is executed in the client (software) that the viewer is using. In the
case of JavaScript, the client is the browser.
• A server-side language is one that runs on the Web server. Examples: PHP, Python
• Interpreted on-the-fly by the client
• Each line is processed as it loads in the browser
• a lightweight programming language ("scripting language")
• used to make web pages interactive
• insert dynamic text into HTML (ex: user name)
• react to events (ex: page load user click)
• get information about a user's computer (ex: browser type)
• perform calculations on user's computer (ex: form validation)

5
Javascript vs Java
• Interpreted by browsers, not compiled
• more relaxed syntax and rules
• fewer and "looser" data types
• variables don't need to be declared
• errors often silent (few exceptions)
• key construct is the function rather than the class
• "first-class" functions are used in many situations
• contained within a web page and integrates with its HTML/CSS
content

6
Including JavaScript in HTML
• Two ways to add JavaScript to Web pages
• Use the <script>…</script> tag
• Include the script in an external file -- more about this later in the
semester
• Initially, we will only use the <script>…</script> tag

<script src="filename" type="text/javascript"></script>


- for external java script code file

<script type=“text/javascript>
document.writeln(“Welcome”);
</script>
- for internal java script code
7
Java script
• Interpreted language
• Lightweight scripting language
• Loosely typed language
• When a variable is declared without value, initially is it undefined datatype.
• Data types: number, string, Boolean, undefined
• Object-based language
• Supports event-driven programming

8
Hello World in JavaScript
<!DOCTYPE html>
<html>
<head> Output
<title>Hello World Example</title>
</head>
<body>
<script type="text/javascript">
<!--
document.write("<h1>Hello, world!</h1>");
//-->
</script>
</body>
</html>
9
The <script>…</script> tag
• The code for the script is contained in the <script>…</script> tag

<script type="text/javascript">
.
.
.
</script>

10
Displaying text
• The document.write() method writes a string of text to the browser

<script type="text/javascript">
<!--
document.write("<h1>Hello, world!</h1>");

//-->
</script>

11
document.write()

Ends in a semicolon

document.write("<h1>Hello,world!</h1>");

Enclosed in quotes -- denotes


a "string"

12
Messaging options
• alert() or window.alert();
• prompt() or window.prompt();
• document.writeln();

13
A JavaScript statement: alert
alert("IE6 detected. Suck-mode enabled.");
JS

• a JS command that pops up a dialog box with a


message

14
Comments in JavaScript
• Two types of comments Multiple line
• Single line Uses /* and */
• Uses two forward slashes (i.e. //)
<script type="text/javascript">

<script type="text/javascript"> <!--

<!-- /* This is a multiple line comment.

// This is my JavaScript comment * The star at the beginning of this line is


optional.
document.write("<h1>Hello!</h1>");
* So is the star at the beginning of this line.
//-->
*/
</script>
document.write("<h1>Hello!</h1>");
//-->
</script>

15
Datatypes Variables
• Numbers var myRoll;
• String var courseCode;
• Variables are Dynamically Typed
• Boolean • Any variable in JavaScript can hold any type of value,
• Undefined and the that type can change midway through the
program

• Coding standard:
• Meaningful variable name must be used
• Naming convention must follow camel case formant.
Eg: myName, myRoomNo
• Each variable must be declared in a new line.

16
Operators
• Arithmetic Operators: +, -, *, /
• Modulus Operator: %
• Increment/Decrement Operator: ++, --, +=, -=, *=, /=, %=
• Comparison operators: ==, !=
• Relation Operator: <, >, <=, >=
• String operators:
• concatenation (+),
• length (n1.length()),
• slice (n1.slice(2,4) and
• Casing: n1.toUpperCase(), n2.toLowerCase()
• Create object: new Date()

17
Control Statements: To change the flow of program
execution. Transfer of control
Selection Statement:
• If
if (condition) { switch(expression) {
// block of code to be executed if case x:
the condition is true
} // code block
• If…else break;
if (condition) { case y:
// block of code to be executed if // code block
the condition is true
} else { break;
// block of code to be executed if default:
the condition is false
} // code block
• Else if ladder }
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
18
Control Statements
• For
Repetition Statement • for
• While(cond)
while (condition) { for (key in object) {
// code block to be executed // code block to be executed
} }
• For in
for (key in object) {
// code block to be executed
}
• For of
for (variable of iterable) {
// code block to be executed
}

19
Functions- define tasks that may be used at many points in a script.
function funname()
{ Function getMilkCost(bottles)
{
} var cost=bottles * 1.5;
return cost;
function funname(arg) }
{ getMilkCost(5);
}

function funname(arg) Predefined functions: Math


Math.random();
{ Math.floor();
return value;
} Recursive Function

20
Arrays
Array Creation
• const cars = ["Saab", "Volvo", "BMW"];
• const cars = new Array("Saab", "Volvo", "BMW"); or cars= new Array(3); or cars= new Array();
Accessing array elements:
• car = cars[0];
Changing array elements:
• cars[0] = "Opel";
Accessing full array elements:
• const cars = ["Saab", "Volvo", "BMW"];
• document.getElementById("demo").innerHTML = cars;
Objects use names to access its "members"
• const person = {firstName:"John", lastName:"Doe", age:46};
• document.getElementById("demo").innerHTML = person.firstName;
Length of Array
• carLen=cars.length();
Adding new elements:
• cars.push(“Audi”);

21
Activity
• Design a web page to display the message “ Welcome User”, when
the user opens the webpage.

22
S7 Objects
Object is an real world entity having state and behaviour (properties and methods).
JavaScript is object-based language.
Everything is considered as object in JavaScript.
Template based, so need of class for object creation.

23
Objects- Object: A named collection of properties (data, state) & methods
(instructions, behavior)

• Everything that JavaScript manipulates, it treats as an object – e.g. a window or a button


• An object has properties – e.g. a window has size, position, status, etc.
• Objects are modified with methods that are associated with that object – e.g. a resize a
window with resizeTo
• JavaScript is not a true object-oriented language like C++ or Java
• It is so because it lacks two key features:
• A formal inheritance mechanism
• Strong typing
• Nevertheless, it does include many key concepts that are part of almost all object-
oriented languages, and therefore is referred as an object-based language

24
Types of Objects
• User-defined objects
• Built-in objects ( such as Date and Math objects)
• Browser objects (such as window, navigator, and history objects)
• Document objects (for example, link, forms and images)

25
User Defined Objects
• In JavaScript, there are three ways to create user-defined objects to
manage enormous tasks and data sets within an application. They
are:
1. By object literal
2. By creating an instance of Object directly (using new keyword)
3. Using object constructor

26
User Defined Objects – Methods to create user-defined objects
II. Using Object instance.

I. Literal method: Using property values of an var myCar = new Object();


object myCar.make = "Indian";
myCar.model = "HigherXLV";
var person = {
myCar.color = "Red";
firstName: "John", myCar.year = 2022;
mycar.myfunction:function() {
lastName: "Herry",
document.write(myCar.make);}
age: 25,
skinColor: "White“ III. Using Object Constructor.
myfunction:function() { function employee(name, age, salary)
document.write(student.firstname); {
this.name = name;
}; this.age = age;
this.salary = salary;
}

var emp = new employee("Micheal", 26, 35000);


27
Example- using Object property
<script>
var person = {
firstName:"John",
lastName:"Herry",
age: 25,
skinColor:"White"
};
// Accessing properties of person object.
document.write("First name: " +person.firstName+ "<br>");
document.write("Last name: " +person.lastName+ "<br>");
document.write("Age: " +person.age+ "<br>");
document.write("Skin color: " +person.skinColor);
</script>

28
Example- Object Instance
<script>
// Creating an instance of Object. hotel.display = function()
var hotel = new Object(); {
// Adding properties to the object hotel. var hotelName = hotel.name; // Accessing name of hotel.
hotel.name = "Park"; document.write("Name of hotel: " +hotelName+ "<br>");
hotel.rooms = 120;
var availableRooms = hotel.checkAvailability();
hotel.booked = 50;
document.write("Rooms left in hotel: " + availableRooms);
// Adding functions to the object hotel.
};
hotel.checkAvailability = function() hotel.display();
{ </script>
return this.rooms - this.booked;
};

29
Example- Object Constructor
<script>
function employee(name, cName, age, salary)
{
// Properties of employee.
this.name = name;
this.cName = cName;
this.age = age;
this.salary = salary;
}
// Creating objects of employee type.
var emp = new employee("Ruchi", "TCS", 25, 60000);
document.write(emp.name+ " " +emp.cName+ " " +emp.age+ " " +emp.salary, "<br>");
var emp = new employee("Tripti", "IBM", 24, 65000);
document.write(emp.name+ " " +emp.cName+ " " +emp.age+ " " +emp.salary, "<br>");
var emp = new employee("Priya", "Wipro", 23, 55000);
document.write(emp.name+ " " +emp.cName+ " " +emp.age+ " " +emp.salary, "<br>");
</script>

30
Built-in Objects
• Math Object
• String Object
• Array Object
• Date Object
• Document Object - DOM
• Window Object

31
Math Object
• Methods: • Methods:
• random(x) • pow(x,y)
• floor(x) • sqrt(x)
• ceil(x) • abs(x)
• sin(x)
• cos(x)
• tanx)
• log(x)
• min(a,b)
• max(a,b)

32
String Object
• Methods
• s.length()
• s.slice(a,b)
• s.toUpperCase()
• s.toLowerCase()

33
Array Object
• Var a= new Array();
• Methods:
• concat()
• join()
• pop()
• push()
• reverse()
• slice()
• shift()
• unshift()… etc

34
Date Object
• Var today=new Date(89,12,3);
• Methods:
• getDate()
• getDay()
• getYear()
• getMonth()
• gethours()
• getminutes()
• getSeconds()
• setDate(new Date()+5);

35
Window Object
• Alert();
• Prompt()
• Open()
• Close()
• Focus()

36
Document Object
• Document.write()
• Document.writeln()

37
S8 Events and Event Handling

38
Events
• Events is state change of an elements
• Example: clicking, keypress, select menu item, and etc.,
• Event Handling: Processing/reacting to events
• Delegation Event Model – Event Handling Model

Sources Listeners

Events generated Handles Events

39
Steps in event handling
1. Define the events and event handler function for all the events
• Normal function definition using javascript
2. Register event with the handler
• Register the event handler to event using addEventListerner()
3. Event generated
• User does any action on HTML elements and generate the events
• Clicking the button
4. Call the handler when event occur
• Execute the event handler function for the event

40
Mouse Events
Event Performed Event Handler Description
click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over


the element
mouseout onmouseout When the cursor of the mouse leaves an
element
mousedown onmousedown When the mouse button is pressed over
the element
mouseup onmouseup When the mouse button is released over
the element
mousemove onmousemove When the mouse movement takes place.

41
Form Events

Event Performed Event Handler Description


focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form


element
change onchange When the user modifies or changes the
value of a form element

42
Window Events

Event Performed Event Handler Description

load onload When the browser finishes the loading of the page

unload onunload When the visitor leaves the current webpage, the
browser unloads it

resize onresize When the visitor resizes the window of the browser

43
Keyboard Events
Event Performed Event Handler Description
Keydown & Keyup onkeydown & onkeyup When the user press and then release the
key

44
Event-driven programming
 JavaScript programs instead wait for user actions called
events and respond to them
 event-driven programming: writing programs driven by
user events
 When an event occurs an event object is thrown to the
handler

45
Event-driven programming

 split breaks apart a string into an array using a


delimiter
 can also be used with regular expressions (seen later)
 join merges an array into a single string, placing a
delimiter between them

46
Registering events to handler
• Using HTML
• Using javascript object
• Using addEventListener()

CS380 47
Using HTML Using Javascript
<body>
<script>
function fun() { <p> Click the following text to see the effect. </p>
alert(“Click Events");
<p id = "para">Click me</p>
<script>
} document.getElementById("para").onclick = function() {
</script> fun()
</head> };
function fun() {
<body>
document.getElementById("para").innerHTML = “Click Events";
<h3> This is an example of using onclick document.getElementById("para").style.color = "blue";
attribute in HTML. </h3>
document.getElementById("para").style.backgroundColor = "yellow";
<p> Click the following button to see the effect. document.getElementById("para").style.fontSize = "25px";
</p>
document.getElementById("para").style.border = "4px solid red";
<button onclick = "fun()">Click me</button> }
</body> </script>

48
Event-driven programming
• <element event='some JavaScript’>

Example:
1. <button onclick="document.getElementById('demo').innerHTML = Date()">The
time is?</button>

2. <button onclick=“this.innerHTML = Date()">The time is?</button>

3. <button onclick=“displayDate()”>The time is?</button>

4. <button onclick ="alert('Hello')">Click me.</button>

49
onload
<html>
<head><title>Javascript Events</title></head>
</br>
<body onload="window.alert('Page successfully loaded');">
Javascript Window events
</body>
</html>

50
Keyboard 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>
</body>

51
onfocus()
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
</script>
</body>
</html>

52
Mouse events
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
function mouseoverevent()
{
alert("This is Mouse events");
}
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>

53
Click Events
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
function clickevent()
{
document.write("Click Events");
}
</script>
<form>
<input type="button" onclick="clickevent()" value="Click Me?"/>
</form>
</body>
</html>

54
addEventListener()
• The addEventListener() method is used to attach an event handler to a particular
element.
• The addEventListener() method is an inbuilt function of JavaScript.
• We can add multiple event handlers to a particular element without overwriting
the existing event handlers.
• Syntax
element.addEventListener(event, function, useCapture);

55
addEventListener()
<button id = "btn"> Click me </button>
<p id = "para"></p>
<script>
document.getElementById("btn").addEventListener("click", fun);
function fun() {
document.getElementById("para").innerHTML = "Hello World" + "<br>"
+ "Welcome to the javaTpoint.com";
}

56
addEventListener()
<html>
<body> function fun2() {
<button id = "btn"> Click me btn.style.width = "100px";
</button> btn.style.height = "100px";
<p id = "para"></p> btn.style.background = "green";
<script> btn.style.color = "white";
function fun() { }
btn.style.width = "100px"; var mybtn = document.getElementById("btn");
btn.style.height = "100px"; mybtn.addEventListener("mouseover", fun);
btn.style.background = "yellow"; mybtn.addEventListener("click", fun1);
btn.style.color = "blue"; mybtn.addEventListener("mouseout", fun2);
} </script>
function fun1() { </body>
</html>
document.getElementById("para").inn
erHTML = "This is second function";
}
57
Activity
• Design a web page as following

Quantity

Unit price

Total price

Calculate

58
S9 Form Validation

59
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. Form validation generally performs two functions.
1. Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled
in. It would require just a loop through each field in the form and check for data.
2. Data Format Validation − Secondly, the data that is entered must be checked for correct form and
value. Your code must include appropriate logic to test correctness of data.

CS380 60
Basic Validation
<script type = "text/javascript"> if( document.myForm.Zip.value == "" ||
// Form validation code will come here. isNaN(document.myForm.Zip.value ) ||
function validate() { document.myForm.Zip.value.length != 5 ) {
alert( "Please provide a zip in the format #####." );
if( document.myForm.Name.value == "" ) {
document.myForm.Zip.focus() ;
alert( "Please provide your name!" ); return false;
document.myForm.Name.focus() ; }
return false; if( document.myForm.Country.value == "-1" ) {
} alert( "Please provide your country!" );
return false;
if( document.myForm.EMail.value == "" ) {
}
alert( "Please provide your Email!" ); return( true );
document.myForm.EMail.focus() ; }
return false;
</script>
}

61
Data Format Validation
<script type = "text/javascript">
function validateEmail() {
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 )) {
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
</script>
62
Activity
• Design a registration form to get the following details and constraints
• firstname, lastname, email, phone
• Validate email
• Make all the fields mandatory
• Phone number – minimum 10 numbers
• Design a login form and check password match for the username.

CS380 63
S9 Exception Handling

64
Exception Handling
• An exception signifies the presence of an abnormal condition which
requires special operable techniques.
• Types of errors:
1. Syntax errors
2. Logical Errors
3. Runtime errors
• Runtime errors are called exception.
• Solved by exception handling
• JavaScript implements the try...catch...finally construct as well as the throw
operator to handle exceptions.

65
try...catch...finally block syntax
<script type = "text/javascript">
try {
// Code to run
[break;]
}
catch ( e ) {
// Code to run if an exception occurs
[break;]
}
[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
</script>

66
Example
<script type = "text/javascript">
function myFunc() {
var a = 100; </head>
var b = 0; <body>
<p>Click the following to see the result:</p>
try {
<form>
if ( b == 0 ) {
<input type = "button" value = "Click Me" onclick = "myFunc();" />
throw( "Divide by zero error." ); </form>
} else { </body>
var c = a / b;
alert(“value of c:” + c ); }
}
catch ( e ) {
alert("Error: " + e );
}
}
</script>
67
The Error Object
• JavaScript has a built in error object that provides error information
when an error occurs.
• The error object provides two useful properties: name and message.
Property Description
name Sets or returns an error name
message Sets or returns an error message (a string)

68
Exception / Error name Types
• EvalError - Raised by eval when it’s used incorrectly
• RangeError - Raised when the numeric value exceeds its range
• ReferenceError - Raised when an invalid reference is used
• SyntaxError - Raised when there is invalid syntax used
• TypeError - Raised when a variable is not if the type expected
• URIError - Raised when encodeURI() or decodeURI() is used incorrectly
• There is an operator called ‘instanceof’ that can be very useful in exception
handling. It can tell you whether a certain error is one of the known types
listed above.
69
Errors

• A SyntaxError is thrown if you try to evaluate code with a syntax error.


• A RangeError is thrown if you use a number that is outside the range
of legal values.
• A ReferenceError is thrown if you use (reference) a variable that has
not been declared
• A TypeError is thrown if you use a value that is outside the range of
expected types
• A URIError is thrown if you use illegal characters in a URI function

70
Example
• let num = 1;
try {
num.toPrecision(500); // A number cannot have 500 significant digits
}
catch(err) {
document.getElementById("demo").innerHTML = err.name; // RangeError
}

71
Example
• let x = 5;
try {
x = y + 1; // y cannot be used (referenced)
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
// ReferenceError
}

72
Example
• try {
eval("alert('Hello)"); // Missing ' will produce an error
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
// SyntaxError
}

73
Example
• let num = 1;
try {
num.toUpperCase(); // You cannot convert a number to upper case
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
// TypeError
}

74
Example
• try {
decodeURI("%%%"); // You cannot URI decode percent signs
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
// URIError
}

75
Example
var arr = null;
try {
console.log( arr[4] ); //will generate a TypeError exception
}
catch (exception) {
if (exception instanceof EvalError)
console.log("An EvalError exception was generated");
else if (exception instanceof RangeError)
console.log("A RangeError exception was generated");
else if (exception instanceof TypeError)
console.log("A TypeError exception was generated");
else //handle all remaining unspecified exceptions
console.log("An exception was generated with the message: "
+ exception.message);
}
finally {
console.log("Inside the 'finally' block");
}
76
• <!DOCTYPE html>
Example
<html>
<body>

<p>Please input a number between 5 and 10:</p>

<input id="demo" type="text">


<button type="button" onclick="myFunction()">Test Input</button>
<p id="p01"></p>

<script>
function myFunction() {
const message = document.getElementById("p01");
message.innerHTML = "";
let x = document.getElementById("demo").value;
try {
if(x.trim() == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
finally {
document.getElementById("demo").value = "";
}
}
</script>

</body>
</html>
77
References
1. Deitel ,Deitel and Nieto, ―Internet and World Wide Web – How to
program‖,4th Edition, Pearson Education Publishers,2009.
2. Jeffrey C. Jackson, “Web Technologies A computer Science
Perspective”, 2011, Pearson, ISBN 9780133001976.

You might also like