Lecture 07 - Javascript - 2
Lecture 07 - Javascript - 2
Harshapriya Rajakaruna
MSc (reading), BSc (Hons)(Special) in IT, BSc (General) in
Applied Sciences (Computer Science/Mathematics), CCNA
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.
• 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)
• toLowerCase()
• A string is converted to lowercase
• concat ()
• Join two or more string
• substr()
• Extracts a part of string
• 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
• See online references for complete list of available methods in these objects:
http://javascript-reference.info/
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).
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
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()
• 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”);
• 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”);
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.sin(x)
Returns the sine value of x
Math.sin(0.0) is 0.0
Math.exp(x) Math.exp(0) is 1
Returns exponential value i.e ex
a = Math.PI;
Math.PI Returns a ∏ value
a = 3.141592653589793
<!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
unshift() Adds new elements to the beginning of an array, and returns the new length
• 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:
71
2023 © SLTC Research University
Form Validation-Example
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.