JAVASCRIPT
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
if (condition) switch (expression)
{ {
do something; case value1:
} statements
else if (Condition)
break;
{
do something else;
} case value2:
else statements
{ break;
do something else; default :
} statements
} 4
Conditional Statements
●
Example if.. else statement:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display a time greeting:</p>
<button onclick="timeFunction()">Get Time
Greeting</button>
<p id="time"></p>
<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;
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 />")
}
//-->
</script>
</body> 6
</html>
Controlling Program Flow(cont.)
●
Loop Statements
a) for c) do…while
for ( var i=0 ;i<10;i++) do
{ {
document.write(“ number” + i) statements
} } while (condition)
b) while c) for( …in…)
while (condition) for (variablename in object)
{ {
statements statement
} }
7
Loop Statements
●
Example for loop:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Loop</h2>
<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>
<h2>JavaScript For/In Loop</h2>
<p>The for/in statement loops through the properties of an object.</
p>
<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>
<h2>JavaScript While Loop</h2>
<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>
<h2>JavaScript Do/While Loop</h2>
<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
}
dosomething(“hello”) Function call
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.)
Name Description Example
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
evaluates an a=999; b=777;
eval(expression) expression and returns document.write(eval(b + a));
the result. // returns 1776
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>
<form action="/action_page.php" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
<p>If you click submit, without filling out the
text field,
your browser will display an error message.</p>
</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!";
Method Description Example
Returns the character at the document.write(myStr.charAt(0));
charAt(index)
specified index //L
Returns the position of the
document.write(myStr.indexOf("at"));
indexOf(string) first found occurrence of a
//12
specified value in a string
Returns the position of the
lastIndexOf(strin document.write(myStr.lastIndexOf("a"));
last found occurrence of a
g) //16
specified value in a string
document.write(myStr.substring(1, 7));
Extracts the characters from
substring(index,i //et's s
a string, between two
ndex) document.write(myStr.substring(2));
specified indices
//t's see what happens! 25
String Object(cont.)
●
Methods manipulating the appearance of the String
Method name Example Returned value
bold() "hi".bold() <b>hi</b>
<FONT
fontcolor() "hi".fontcolor("green") COLOR="green“>hi</FONT
>
fontsize() "hi".fontsize(1) <FONT SIZE="1">hi</FONT>
italics() "hi".italics() <I>hi</I>
strike() "hi".strike() <STRIKE>hi</STRIKE>
sup() "hi".sup() <SUP>hi</SUP>
toLowerCase() "UPPERcase".toLowerCase() uppercase
toUpperCase() "UPPERcase".toUpperCase() UPPERCASE
26
String Object(cont.)
●
String object example:
<script>
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
document.getElementById("p1").innerHTML = sln;
var str = "Apple, Banana, Kiwi";
var res = str.substring(7,13);
document.getElementById("p2").innerHTML = res;
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
document.getElementById("p3").innerHTML = pos;
</script>
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
push(element Adds new elements to the end document.write(arr1.push(“D”););
) of an array, and returns the //4 (Length of the array)
new length 29
//and arr1[3]=“D”
Array Object(cont.)
●
Associative Arrays: The Arrays That Aren't
●
Associative arrays let you specify key-value pairs.
●
Associative array is just like an ordinary array, except that instead of
the indices being numbers, they’re strings, which can be a lot easier
to remember and reference:
●
Although the keys for an associative array have to be strings, the
values can be of any data type, including other arrays or associative
arrays.
●
Syntax:
<script>
var assocArray = new Array( );
assocArray[“Ahmed"] = “Excellent";
assocArray[“Tareq"] = “pass";
</script>
30
Array Object(cont.)
●
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