Session 2
Session 2
1
Outline
●
Controlling Program Flow
●
Javascript Functions
●
Javascript Events
●
What are JS Objects?
●
Built-in Objects
2
Controlling Program Flow
●
Control Statements that can be used are:
●
Conditional Statements
– if ….else
– switch/case
●
Loop Statements
– for
– while
– do…while
3
Controlling Program Flow(cont.)
●
Conditional Statements:
a) if….else b) switch / case
●
Example if.. else statement:
<!DOCTYPE html>
<html>
<body>
<script>
function timeFunction() {
var hour = new Date().getHours();
var greeting;
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
document.getElementById("time").innerHTML = greeting;
}
</script>
</body>
</html> 5
Conditional Statements(cont.)
●
Example switch statement:
<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
switch (grade) {
case 'A': document.write("Good job<br />");
break;
●
Loop Statements
a) for c) do…while
for ( var i=0 ;i<10;i++) do
{ {
document.write(“ number” + i) statements
} } while (condition)
7
Loop Statements
●
Example for loop:
<!DOCTYPE html>
<html>
<body>
<p id="test"></p>
<script>
var text = "";
var i;
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("test").innerHTML = text;
</script>
</body>
</html>
8
Loop Statements(cont.)
●
The For/In Loop example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var txt = "";
var person = {fname:"John", lname:"Doe", age:25};
var x;
for (x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
9
Loop Statements(cont.)
●
The while loop example:
<!DOCTYPE html>
<html>
<body>
<p id="testWhile"></p>
<script>
var text = "";
var i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("testWhile").innerHTML = text;
</script>
</body>
</html>
10
Loop Statements(cont.)
●
The do/while example:
<!DOCTYPE html>
<html>
<body>
<p id="testDoWhile"></p>
<script>
var text = ""
var i = 0;
do {
text += "<br>The number is " + i;
i++;
}
while (i < 10);
document.getElementById("testDoWhile").innerHTML = text;
</script>
</body>
</html> 11
JavaScript Loop Control
●
●
Breaking Loops :
1) break statement : The break statement will break the loop and continue
executing the code that follows after the loop (if any).
2) continue statement: The continue statement will break the current loop and
continue with the next value.
<script>
var text = "";
var i;
for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
12
JavaScript User-defined Functions
function dosomething(x)
Function parameters
{
statements
}
function sayHi()
{
statements
return “hi”
}
z= sayHi() The value of z is “hi”
13
User-defined Functions(cont.)
●
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"The temperature is " + toCelsius(77) + " Celsius";
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
</script>
</body>
</html>
14
JavaScript Built-in Functions
Name Example
parseInt parseInt("3") //returns 3
parseInt(“3a”) //returns 3
parseInt(“a3”) //returns NaN
parseFloat parseFloat("3.55") //returns 3.55
parseFloat(“3.55a”) //returns 3.55
parseFloat(“a3.55”) //returns NaN
15
JavaScript Built-in Functions(cont.)
document.write(isFinite(2.2345))
returns true if the //returns true
isFinite(num)
number is finite, else
(used to test number)
false document.write(isFinite(“Hello”))
//returns false
validate the argument document.write(isNaN(0/0))
isNaN(val) for a number and //returns true
returns true if the given
(used to test value) value is not a number document.write(isNaN("348"))
else returns false. //returns false
16
JavaScript Events
●
What is an Event ?
●
JavaScript's interaction with HTML is handled through events that
occur when the user or the browser manipulates a page.
●
When the page loads, it is called an event. When the user clicks a
button, that click too is an event. Other examples include events like
pressing any key, closing a window, resizing a window, etc.
●
Examples of HTML Events:
1) onclick Event Type
2) onsubmit Event Type
3) onmouseover and onmouseout
17
Complete example for events
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say
Hello" />
</form>
</body>
</html>
18
JavaScript Forms
●
JavaScript Form Validation
a) HTML Form b) JavaScript validation
<form name="myForm" action="/ function validateForm() {
action_page.php" onsubmit="return var x = document.forms["myForm"]
validateForm()" method="post"> ["fname"].value;
if (x == "") {
Name: <input type="text" name="fname"> alert("Name must be filled
<input type="submit" value="Submit"> out");
</form> document.myForm.fname.focus() ;
return false;
}
}
19
Automatic HTML Form Validation
<!DOCTYPE html>
<html>
<body>
</body>
</html>
20
What are JS Objects?
●
JavaScript is an Object Oriented Programming (OOP)
language.
●
Objects are composed of attributes. If an attribute contains
a function, it is considered to be a method of the object,
otherwise the attribute is considered a property.
21
JavaScript Objects
●
JavaJavaScript Objects fall into 4 categories:
1) User-Defined Objects: Objects that you, as a JavaScript
developer, create and use.
2) Built – in Objects: Objects that are provided with JavaScript to
make your life as a JavaScript developer easier.
3) BOM Objects “Browser Object Model”: It is a collection of
objects that are accessible through the global objects window.
The browser objects deal with the characteristic and properties
of the web browser.
4) DOM Objects “Document Object Model”: Objects provide the
foundation for creating dynamic web pages. The DOM provides
the ability for a JavaScript script to access, manipulate, and
extend the content of a web page dynamically.
22
JavaScript Built-in Objects
1) String 6)Boolean
2)Number 7)RegExp
3)Array 8)Error
4)Date 9)Object
5)Math
23
String Object
●
Enables us to work with and manipulate strings of text.
●
String Objects have:
– One Property:
length : gives the length of the String.
– Methods that fall into three categories:
●
Manipulate the contents of the String
●
Manipulate the appearance of the String
●
Convert the String into an HTML element
24
String Object(cont.)
●
String Methods:
1)Methods manipulating the contents of the String
var myStr = "Let's see what happens!";
●
Methods manipulating the appearance of the String
26
String Object(cont.)
●
String object example:
<script>
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
document.getElementById("p1").innerHTML = sln;
27
Array Object
●
The Array object lets you store multiple values in a single
variable. It stores a fixed-size sequential collection of elements
of the same type. An array is used to store a collection of data,
but it is often more useful to think of an array as a collection of
variables of the same type.
●
To decalre an array <script>
var colorArray = new Array();
colorArray [0]=“red”;
colorArray [1]=“blue”;
colorArray [2]=“green;
//OR
var colorArray = new Array(3);
colorArray [0]=“red”;
colorArray [1]=“blue”;
colorArray [2]=“green”;
//OR
var colorArray = new Array(“red”,”blue”,”green”);
</script> 28
Array Object(cont.)
●
Array Methods
var arr1=new Array(“A”,”B”,”C”); var arr2 = new Array(“1”,”2”,”0”)
Methods Description Example
concat(array Joins two or more arrays, and document.write(arr1.concat(arr2));
) returns a copy of the joined //A,B,C,1,2,0
arrays
join() Joins all elements of an array document.write(arr1.join());
into a string //A,B,C
document.write(arr1.join(“*”));
//A*B*C
reverse() Reverses the order of the document.write(arr1.reverse());
elements in an array //C,B,A
pop() Removes the last element of an document.write(arr1.pop());
array, and returns that element //C, and the length becomes 2
●
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
document.getElementById("demo").innerHTML =
person[0] + " " + person.length;
</script>
</body>
</html>
31
Boolean Objects
●
The Boolean object is used to convert a non-Boolean value to a
Boolean value (true or false).
●
All the following lines of code create Boolean objects with an initial
value of false:
var myBoolean=new Boolean()
var myBoolean=new Boolean(0)
var myBoolean=new Boolean(null)
var myBoolean=new Boolean("")
var myBoolean=new Boolean(false)
var myBoolean=new Boolean(NaN)
●
And all the following lines of code create Boolean objects with an
initial value of true:
var myBoolean=new Boolean(true)
var myBoolean=new Boolean("true")
var myBoolean=new Boolean("false“)
var myBoolean=new Boolean("Richard")
32
Questions?
33