0% found this document useful (0 votes)
3 views78 pages

Lecture 07 - Javascript - 2

The document provides an overview of client-side web technologies, specifically focusing on JavaScript functions, event handling, and the Document Object Model (DOM). It explains the syntax and usage of functions, built-in functions, event-driven programming, and how to manipulate HTML elements using JavaScript. Additionally, it covers error handling, JavaScript objects, and methods for accessing and modifying document properties in web pages.

Uploaded by

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

Lecture 07 - Javascript - 2

The document provides an overview of client-side web technologies, specifically focusing on JavaScript functions, event handling, and the Document Object Model (DOM). It explains the syntax and usage of functions, built-in functions, event-driven programming, and how to manipulate HTML elements using JavaScript. Additionally, it covers error handling, JavaScript objects, and methods for accessing and modifying document properties in web pages.

Uploaded by

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

CIT112 –Web Technologies

Lecture 05 – Client Side Web Technologies :Javascript

Harshapriya Rajakaruna
MSc (reading), BSc (Hons)(Special) in IT, BSc (General) in
Applied Sciences (Computer Science/Mathematics), CCNA

Network Manager, IT Center, Rajarata University of Sri


Lanka

2023 © SLTC Research University 2


Functions and Procedures
• A function in a JavaScript is a set of statements that
performs a specific task (a procedure).
• A function will be executed by an event or by a call to that
function.
• Functions can be defined both in the <head> and in the
<body> section of a document. However, to assure that
the function is read/loaded by the browser before it is
called, it could be wise to put it in the <head> section.
• A function can be called from anywhere within the page (or
even from other pages if the function is embedded in an
external .js file).

3
2023 © SLTC Research University
Why Functions ?
• With functions you can reuse code
• You can write code that can be used many times.
• You can use the same code with different arguments, to produce different
results.

2023 © SLTC Research University


Function
• Syntax
function name(parameter1, parameter2, parameter3) {
// code to be executed
}

• Example
// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}
 statements placed into functions can be evaluated in
response to user events
5
2023 © SLTC Research University
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)

2023 © SLTC Research University


Function Return
Functions often compute a return value. The return value is "returned"
back to the "caller":

2023 © SLTC Research University


Example 1

2023 © SLTC Research University


Example 2

2023 © SLTC Research University


Built-In Functions
• eval(expr)
• evaluates an expression or statement
• eval("3 + 4"); // Returns 7 (Number)
• eval("alert('Hello')"); // Calls the function alert('Hello')
• isFinite(x)
• Determines if a number is finite
• isNaN(x)
• Determines whether a value is “Not a Number”

2023 © SLTC Research University


Built-In Functions(2)
• toUpperCase()
• A string is converted to uppercase

• toLowerCase()
• A string is converted to lowercase

• concat ()
• Join two or more string

2023 © SLTC Research University


Built-In Functions(3)
• trim()
• Remove whitespace from both sides of a strings

• substr()
• Extracts a part of string

2023 © SLTC Research University


Built-In Functions (4)
• parseInt(s)
• parseInt(s, radix)
• Converts string literals to integers
• Parses up to any character that is not part of a valid integer
• parseInt("3 chances") // returns 3
• parseInt(" 5 alive") // returns 5
• parseInt("How are you") // returns NaN
• parseInt("17", 8) // returns 15

• parseFloat(s)
• Finds a floating-point value at the beginning of a string.
• parseFloat("3e-1 xyz") // returns 0.3
• parseFloat("13.5 abc") // returns 13.5

2023 © SLTC Research University


Events
• An event occurs as a result of some activity
• e.g.:
• A user clicks on a link in a page
• Button was clicked
• Page finished loaded
• Mouse cursor enter an area
• A preset amount of time elapses
• A form is being submitted

2023 © SLTC Research University


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
15
2023 © SLTC Research University
Event Handlers
• Event Handler – a segment of codes (usually a function)
to be executed when an event occurs

• We can specify event handlers as attributes in the HTML


tags.

• The attribute names typically take the form "onXXX"


where XXX is the event name.
• e.g.:
<a href="…" onClick="alert('Bye')">Other
Website</a>

2023 © SLTC Research University


Event Handlers

For a complete list, see http://www.w3schools.com/htmldom/dom_obj_event.asp

2023 © SLTC Research University


onclick Event Handler Example

2023 © SLTC Research University


onload Event Handler Example

2023 © SLTC Research University


onmouseover & onmouseout Event Handler

2023 © SLTC Research University


Build-In JavaScript Objects
Object Description
Array Creates new array objects
Boolean Creates new Boolean objects
Date Retrieves and manipulates dates and times
Error Returns run-time error information
Function Creates new function objects
Math Contains methods and properties for performing mathematical
calculations
Number Contains methods and properties for manipulating numbers.
String Contains methods and properties for manipulating text strings

• See online references for complete list of available methods in these objects:
http://javascript-reference.info/

2023 © SLTC Research University


String Object (Some useful methods)
• length
• A string property that tells the number of character in the string
• charAt(idx)
•Returns the character at location "idx"
• toUpperCase(), toLowerCase()
•Returns the same string with all uppercase/lowercase letters
• substring(beginIdx)
•Returns a substring started at location "beginIdx"
• substring(beginIdx, endIdx)
•Returns a substring started at "beginIdx" until "endIdx" (but not
including "endIdx"
• indexOf(str)
•Returns the position where "str" first occurs in the string

2023 © SLTC Research University


Error and Exception Handling in JavaScript
• Javascript makes no distinction between Error and Exception
(Unlike Java)
• Handling Exceptions
• The try … catch … finally block
• Similar to Java try … catch … finally block
• For handling exceptions in a code segment
• Use throw statement to throw an exception
• You can throw value of any type
• The Error object
• Default object for representing an exception
• Each Error object has a name and message properties

2023 © SLTC Research University


Exception handling

2023 © SLTC Research University


Exception handling -example

2023 © SLTC Research University


What is the DOM?
• The DOM is a W3C (World Wide Web Consortium) standard.
• The DOM defines a standard for accessing documents:
• "The W3C Document Object Model (DOM) is a platform and
language-neutral interface that allows programs and scripts to
dynamically access and update the content, structure, and style of a
document."
• The W3C DOM standard is separated into 3 different parts:
• Core DOM - standard model for all document types
• XML DOM - standard model for XML documents
• HTML DOM - standard model for HTML documents

2023 © SLTC Research University


What is the HTML DOM?
• The HTML DOM is a standard object model
and programming interface for HTML. It defines:
• The HTML elements as objects
• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements

2023 © SLTC Research University


JavaScript - HTML DOM Methods
• HTML DOM methods are actions you can perform (on
HTML Elements).
• HTML DOM properties are values (of HTML Elements) that
you can set or change.

2023 © SLTC Research University


Document Object Model (DOM)
• When a web page is loaded, the browser creates
a Document Object Model of the page.
• Representation of the current web page as a tree of
Javascript objects
• allows you to view/modify page elements in script code
after page has loaded
• client side = highly responsive interactions
• browser-independent
• allows progressive enhancement.

2023 © SLTC Research University


Document Object Model (DOM)(2)
• most JS code manipulates
elements on an HTML page
• we can examine elements' state
• e.g. see whether a box is checked
• we can change state
• e.g. insert some new text into a div
• we can change styles
• e.g. make a paragraph red

30
2023 © SLTC Research University
The DOM Programming Interface
• The HTML DOM can be accessed with JavaScript (and
with other programming languages).
• In the DOM, all HTML elements are defined as objects.
• The programming interface is the properties and methods
of each object.
• A property is a value that you can get or set (like
changing the content of an HTML element).
• A method is an action you can do (like add or deleting an
HTML element).

2023 © SLTC Research University


The getElementById Method
• The most common way to access an HTML element is to
use the id of the element.
• In the example above the getElementById method used
id="demo" to find the element.
The innerHTML Property
• 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.
• The innerHTML property can be used to get or change any
HTML element, including <html> and <body>.

2023 © SLTC Research University


The HTML DOM Document Object
• The document object represents your web page.
• If you want to access any element in an HTML page, you always
start with accessing the document object.
• Below are some examples of how you can use the document
object to access and manipulate HTML.

2023 © SLTC Research University


Example
• The following example changes the content (the innerHTML) of the
<p> element with id="demo":
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>

2023 © SLTC Research University


Accessing elements: document.getElementById
var name = document.getElementById("id");
JS

<button onclick="changeText();">Click me!</button>


<span id="output">replace me</span>
<input id="textbox" type="text" /> HTML

function changeText() {
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");

textbox.style.color = "red";
span.innerHTML = textBox.value;

} JS

35
2023 © SLTC Research University
Example 2

2023 © SLTC Research University


Contd…
 document.getElementById returns the DOM object for an
element with a given id
 can change the text inside most elements by setting the
innerHTML property
 can change the text in form controls by setting the value
property

37
2023 © SLTC Research University
JavaScript Objects
• Real Life Objects, Properties, and Methods
• In real life, a car is an object.
• A car has properties like weight and color, and methods like start and
stop:
• Object Properties
1. car.name = Celerio
2. car.model = 2018
3. car.weight = 850kg
4. car.color = silky silver
• Methods
1. car.start()
2. car.drive()
3. car.brake()
4. car.stop()

2023 © SLTC Research University


JavaScript Objects(2)
• All cars have the same properties, but the property values
differ from car to car.
• All cars have the same methods, but the methods are
performed at different times.

2023 © SLTC Research University


JavaScript Objects(3)
<!DOCTYPE html>
<html>
<body>
<p>Creating a JavaScript Variable.</p>
<p id="demo"></p> You have already learned that JavaScript variables are
containers for data values.
<script> This code assigns a simple value (Celerio) to
a variable named car:
var car = “Celerio";
document.getElementById("demo").innerHTML = car;
</script>
</body>
</html>
2023 © SLTC Research University
JavaScript Objects(4)
• Objects are variables too. But objects can contain many values.
• This code assigns many values (Celerio, 2018, silky silver) to
a variable named car:
• The values are written as name:value pairs (name and value
separated by a colon).
<!DOCTYPE html>
<html><body>
<p>Creating a JavaScript Object.</p>
<p id="demo"></p>
<script>
var car = {type:“Celerio", model:“2018", color:“silky silver"};
document.getElementById("demo").innerHTML = car.type;
</script></body></html>
2023 © SLTC Research University
Object Properties
• The name:values pairs (in JavaScript objects) are
called properties.
• var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
• Object Methods:
• Methods are actions that can be performed on objects.
• Methods are stored in properties as function definitions.

2023 © SLTC Research University


Object Definition
• You define (and create) a JavaScript object with an object
literal:
• Example
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};

2023 © SLTC Research University


Accessing Object Properties
• You can access object properties in two ways:
• objectName.propertyName
Or
objectName["propertyName"]
• Example1
• person.lastName;
• Example2
• person["lastName"];

2023 © SLTC Research University


Example

2023 © SLTC Research University


Example

2023 © SLTC Research University


Accessing Object Methods
• You access an object method with the following syntax:
• objectName.methodName()
• Example
• name = person.fullName();

2023 © SLTC Research University


Example

2023 © SLTC Research University


The Document Object
• A document is a web page that is being either displayed or created. The
document has a number of properties that can be accessed by JavaScript
programs and used to manipulate
• the content of the page.
• write or writeln
• Html pages can be created on the fly using JavaScript. This is done by
using the write or writeln methods of the document object.
• Syntax:document.write (“String”); document.writeln (“String”);
• In this document is object name and write () or writeln () are methods.
Symbol period is used as connector between object name and method
name. The difference between these two methods is carriage form feed
character that is new line character automatically added into the document.
• Exmaple: document.write(“<body>”); document.write(“<h1> Hello </h1>”);

2023 © SLTC Research University


The Document Object(2)
• bgcolor and fgcolor
These are used to set background and foreground(text) color to
webpage. The methods accept either hexadecimal values or common
names for colors.
Syntax: document.bgcolor=”#1f9de1”; document.fgcolor=“silver”;
• anchors
The anchors property is an array of anchor names in the order in which
they appear in the HTML Document. Anchors can be accessed like this:
• Syntax:
• document.anchors[0];
• document.anchors[n-1];
• Forms
Another array, this one contains all of the HTML forms. By combining
this array with the individual form objects each form item can be
accessed.
2023 © SLTC Research University
The Window Object
• The window object is used to create a new window and to control the
properties of window.

• Window object supports three types of message boxes.


• Alert box
• Confirm box
• Prompt box

• Alert box is used to display warning/error messages to user. It


displays a text string with OK button.
• Syntax: window. Alert (“Message”);

2023 © SLTC Research University


The Window Object(2)

• Confirm Box
is useful when submitting form data. This displays a
window containing message with two buttons: OK and
Cancel. Selecting Cancel will abort the any pending
action, while OK will let the action proceed.
• Syntax
window.confirm(“String”);

2023 © SLTC Research University


The Window Object(3)

• Prompt box used for accepting data from user through keyboard.
This displays simple window that contains a prompt and a text field in
which user can enter data. This method has two parameters: a text
string to be used as a prompt and a string to use as the default value. If
you don‟t want to display a default then simply use an empty string.
• Syntax
Variable=window.prompt(“string”,”default value”);

2023 © SLTC Research University


The Form Object
• Two aspects of the form can be manipulated through JavaScript.
First, most commonly and probably most usefully, the data that
is entered onto your form can be checked at submission.
Second you can actually build forms through JavaScript.
• Form object supports three events to validate the form
onClick = “method()”
• This can be applied to all form elements. This event is triggered
when the user clicks on the element.
onSubmit = “method()”
• This event can only be triggered by form itself and occurs when
a form is submitted.
onReset = “method()”
• This event can only be triggered by form itself and occurs when
a form is reset.
2023 © SLTC Research University
The Math Object
• The Math object holds all mathematical functions and values.
All the functions and attributes used in complex mathematics
must be accessed via this object.
• Syntax:
• Math.methodname();
• Math.value;

2023 © SLTC Research University


Method Description Example

Math.abs(x) Math.abs(-20) is 20
Returns the absolute value
Math.ceil(5.8) is 6
Math.ceil(x) Returns the ceil value
Math.ceil(2.2) is 3
Math.floor(5.8) is 5
Math.floor(x) Returns the floor value
Math.floor(2.2) is 2

Math.round(x) Math.round(5.8) is 6
Returns the round value, nearest integer value
Math.round(2.2) is 2
Removes the decimal places it returns only Math.trunc(5.8) is 5
Math.trunc(x) Math.trunc(2.2) is 2
integer value
Math.max(2,3) is 3
Math.max(x,y) Returns the maximum value
Math.max(5,2) is 5
Math.min(2,3) is 2
Math.min(x,y) Returns the minimum value
Math.min(5,2) is 2

Math.sqrt(x) Returns the square root of x Math.sqrt(4) is 2

2023 © SLTC Research University


Method Description Example

Math.pow(a,b) This method will compute the ab Math.pow(2,4) is 16

Math.sin(x)
Returns the sine value of x
Math.sin(0.0) is 0.0

Math.cos(x) Returns cosine value of x Math.cos(0.0) is 1.0

Math.tan(x) Returns tangent value of x Math.tan(0.0) is 0

Math.exp(x) Math.exp(0) is 1
Returns exponential value i.e ex

Math.random(x) Generates a random number in between 0 and 1 Math.random()

Math.log(x) Display logarithmic value Math.log(2.7) is 1

a = Math.PI;
Math.PI Returns a ∏ value
a = 3.141592653589793

2023 © SLTC Research University


The Date Object
• This object is used for obtaining the date and time. .
• new Date(); Constructs an empty date object.
• new Date(“String”); Creates a Date object based upon the
contents of a text string.
• new Date(year, month, day[,hour, minute, second] ); Creates
a Date object based upon the numerical values for the year,
month and day.
var dt=new Date();
document.write(dt); // Fri Nov 11 2022 01:47:11 GMT+0530 (Sri Lanka
Standard Time)

2023 © SLTC Research University


<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
</body>
</html>
output:
Fri Nov 11 2022 01:48:40 GMT+0530 (Sri Lanka Standard Time)

2023 © SLTC Research University


JavaScript Date Methods
• Date methods let you get and set date values (years, months,
days, hours, minutes, seconds, milliseconds)
Method Description

getDate() Get the day as a number (1-31)

getDay() Get the weekday as a number (0-6)

getFullYear() Get the four digit year (yyyy)

getHours() Get the hour (0-23)

getMilliseconds() Get the milliseconds (0-999)

getMinutes() Get the minutes (0-59)

getMonth() Get the month (0-11)

2023 © SLTC Research University


JavaScript Arrays
• JavaScript arrays are used to store multiple values in a single variable.
• Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
var array-name = [item1, item2, ...];
• Using the JavaScript Keyword new
The following example also creates an Array, and assigns values to it:
var cars = new Array("Saab", "Volvo", "BMW");
• Access the Elements of an Array
You refer to an array element by referring to the index number.
var name = cars[0];
This statement modifies the first element in cars:
cars[0] = "Opel";
61
2023 © SLTC Research University
JavaScript Arrays(2)
Displaying Arrays

<!DOCTYPE html>
<html>
<body>

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

<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>

</body>
</html>

62
2023 © SLTC Research University
JavaScript Arrays(3)
Arrays are Objects
• Arrays are a special type of objects. The typeof operator in
JavaScript returns "object" for arrays.
• Array Properties and Methods
The real strength of JavaScript arrays are the built-in array
properties and methods:
Examples
var x = cars.length; // The length property returns the
number of elements in cars
var y = cars.sort(); // The sort() method sort cars in
alphabetical order

63
2023 © SLTC Research University
Array Object Methods
Method Description

concat() Joins two or more arrays, and returns a copy of the joined arrays

indexOf() Search the array for an element and returns its position
join() Joins all elements of an array into a string

lastIndexOf() Search the array for an element, starting at the end, and returns its position

pop() Removes the last element of an array, and returns that element
push() Adds new elements to the end of an array, and returns the new length
reverse() Reverses the order of the elements in an array

shift() Removes the first element of an array, and returns that element

slice() Selects a part of an array, and returns the new array


sort() Sorts the elements of an array
splice() Adds/Removes elements from an array
toString() Converts an array to a string, and returns the result

unshift() Adds new elements to the beginning of an array, and returns the new length

valueOf() Returns the primitive value of an array


64
2023 © SLTC Research University
Array Object Methods(2)
• Concat():Joins two or more arrays, and returns a copy of the joined arrays.
Syntax: array.concat(array1,array2…..);
Ex:
var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var kai = ["Robin"];
var children = hege.concat(stale,kai);

• indexOf():this method searches the array for the specified item, and returns its position.
Syntax: array.indexOf(item);
Ex: var fruits=[“Banana”,Orange”,”Apple”,”Mango”];
var x=fruits.indexOf(“Apple”);
Here the value of x is:2 i.e. Apple is at position 2.

65
2023 © SLTC Research University
Array Object Methods(3)
• Join():The join() method joins the elements of an array into a string, and returns the string.
The elements will be separated by a specified separator. The default separator is
comma (,).
Syntax: array.join();
Ex: var fruits=[“Banana” Orange”,”Apple”,”Mango”];
var x=fruits.join();
the result of x will be Banana,Orange,Apple,Mango.

• Slice(): The slice() method returns the selected elements in an array, as a new array
object.
The slice() method selects the elements starting at the given start argument, and
ends at, but does not include, the given end argument.
Syntax: array.slice (start, end);
Ex: var fruits=[“Banana”,Orange”,”Apple”,”Mango”];
var x=fruits.slice(1,3);
the result of x will be [Orange,Apple];
66
2023 © SLTC Research University
Array Object Methods(3)
• Splice(): The splice() method adds/removes items to/from an array, and
returns the removed item(s).
Syntax: array.splice(index,howmany,item1,item2….);
Ex: var fruits=[“Banana”,Orange”,”Apple”,”Mango”];
fruits.splice(2,1,”Lemon”,”Kiwi”);
the result of fruits will be [Banana,Orange,Lemon,Kiwi,Mango]
• Appending an element / getting the last element:
Ex. arr.push(3);
var element = arr.pop();
• Reading the number of elements (array length):
Ex. arr.length;
• Finding element's index in the array:
Ex. arr.indexOf(1);
67
2023 © SLTC Research University
Form Validation
• HTML form validation can be done by JavaScript.

• If a form field (fname) is empty, this function alerts a message, and returns
false, to prevent the form from being submitted:

2023 © SLTC Research University


Form Validation –Numeric Input

2023 © SLTC Research University


Form Validation -Automatic

2023 © SLTC Research University


Form Validation Example
• A form to get user name and password. Validation required
to check
• has the user left required fields empty
• has the user entered text in correct length

71
2023 © SLTC Research University
Form Validation-Example

2023 © SLTC Research University


2023 © SLTC Research University
DYNAMIC HTML
• Dynamic HTML, or DHTML, is for a collection of technologies
used together to create interactive and animated by using a
combination of a static markup language (such as HTML), a
client-side scripting language (such as JavaScript), a
presentation definition language (such as CSS), and the
Document Object Model.
• DHTML is combination of HTML, CSS and JavaScript. It gives
pleasant appearance to web page.

2023 © SLTC Research University


DYNAMIC HTML
• Difference between HTML and DHTML
HTML DHTML

HTML is used to create static web pages. DHTML is used to create dynamic web
pages.
HTML is consists of simple html tags. DHTML is made up of HTML tags+cascading
style sheets+javascript.
Creation of html web pages is simplest but Creation of DHTML is complex but more
less interactive. interactive.

2023 © SLTC Research University


DHTML-Uses
• DHTML allows authors to add effects to their pages that are
otherwise difficult to achieve.
• For example, DHTML allows the page author to:
• Animate text and images in their document, independently moving
each element from any starting point to any ending point, following a
predetermined path or one chosen by the user.
• Embed a ticker that automatically refreshes its content with the
latest news, stock quotes, or other data.
• Use a form to capture user input, and then process and
respond to that data without having to send data back to the
server.
• Include rollover buttons or drop-down menus.

2023 © SLTC Research University


References
• https://www.w3schools.com

2023 © SLTC Research University


2023 © SLTC Research University

You might also like