Chapter 4 IP
Chapter 4 IP
CHAPTER FOUR
JavaScript
Mulugeta G..
2
Contents
JavaScript Basics
JavaScript Functions
JavaScript
• Growth of the WWW has resulted in a demand for dynamic and
dynamic content
• is a lightweight, interpreted programming language of the Web.
• Client-side technology
JavaScript
Advantages of JavaScript
• JavaScript allows interactivity such as:
• Implementing form validation
JavaScript
Why JavaScript
• A web document can consist of up to three layers
• Content--> HTML
• Presentation--> CSS
• Behavior--> JavaScript
6
JavaScript
Content Layer
• content layer is always present
JavaScript
Presentation Layer
• defines how the content will appear to a human being who
browser
• Example: content can also be converted to synthetic
speech for users who have impaired vision or reading
difficulties.
8
JavaScript
Behavior Layer
• The behavior layer involves real-time user interaction with
the document
• This task is normally handled by JavaScript
<script language=“JavaScript”
src=“your_source_file.js”></script>
Advantages of external JavaScript
• It separates HTML and code
• It makes HTML and JavaScript easier to read and maintain
• Cached JavaScript files can speed up page loads
11
JavaScript
Tells where the JavaScript starts
<html>
<body>
<script type=“text/javascript”>
document.write(“Hello World!”);
</script>
</body> Commands for writing output to a page
</html>
Example
<html><head></head>
<body>
<script type="text/javascript">
alert('Hello JavaScript!');
</script>
</body>
</html>
<html><head></head>
<body>
<script type="text/javascript">
document.write('JavaScript rulez!');
</script>
</body>
</html>
13
Example
<html>
<html> <head>
<head> <script type="text/javascript">
function test (message) {
<script src="xyz.js"> alert(message);
</script> }
</head> A separate file </script>
</head>
<body> <body>
</body> <img src="logo.gif"
</html> onclick="test('clicked!')" />
</body>
</html>
14
Methods/Popup boxes
Using alert() Method
• It is the easiest methods to use amongst alert(), prompt() and
confirm().
• You can use it to display textual information to the user
(simple and concise).
• The user can simply click “OK” button to close it.
<head>
<script language=“JavaScript”>
alert(“An alert triggered by JavaScript”);
</script>
</head>
15
Methods/Popup boxes
Using confirm() Method
• This box is used to give the user a choice either OK or
Cancel button.
• It is very similar to the “alert()” method.
• Used if you want the user to verify or accept something.
.
<head>
<script language=“JavaScript”>
confirm(“Are you happy with the class?”);
</script>
</head>
16
Methods/Popup boxes
Using prompt() Method
• This is the only one that allows the user to type in his own
Example
<script language="JavaScript">
alert("This is an Alert method");
confirm("Are you OK?");
prompt("What is your name?");
prompt("How old are you?","20");
</script>
18
JavaScript Syntax
• The JavaScript syntax is similar to C# and Java
• Variables (type-less)
• Comments
Variables
• Variables
• are containers for Storing Data
• JavaScript allows you to declare and use variables to store values
• How to assign a name to a variable?
• JavaScript is Case-sensitive
Variables
Scope of Variables
• When you use a variable in a JavaScript program that uses functions.
• Global variable is one that is declared outside a function and is
accessible in any part of your program
• Local variable is declared inside a function and stops existing
when the function ends
Example:
• Legal Variables: My_variable, $my_variable,_my_variable
• Illegal Variables: 1my_example, @my_variable,
#my_variable, ~my_variable
21
Variable Declaration
• JS uses the keywords var, let and const to declare variables.
• Example: let x;
x = 6;
<head>
<script language=“JavaScript”>
var id;
id = prompt(“What is your student id number?”);
alert(id);
name = prompt(“What is your name?", "No name”);
alert(name);
</script>
</head>
22
Data types
• JavaScript allows the same variable to contain different types of data values
• Undefined: the variable has been created by not yet assigned a value
23
Strings
• Strings can store a sequence of alphanumeric characters, spaces and
special characters
• enclosed in single (‘) or in double quotation marks (“)
• What is the data type of “100”? String but not number type
<head>
<script language=“JavaScript”>
document.write(“This is a string.”);
document.write(“This string contains ‘quote’.”);
var myString = “My testing string”;
alert(myString);
</script>
</head>
24
Object
• Object anything in the real world
• E.g. (cars, dogs, money, books, … )
• In web browser, objects are browser window itself, forms, buttons,
text boxes, …
• Methods are things that objects can do.
Array
• Array
• Syntax:
• Arrays in JavaScript are represented by the Array Object, we need to
• first element of the array is “Array[0]” until the last one Array[i-1].
• We have myArray[0,1,2,3,4].
26
Array
• Declaring new empty array:
var arr = new Array();
• Declaring an array holding few elements:
var arr = [1, 2, 3, 4, 5];
• Appending an element / getting the last element:
arr.push(3);
var element = arr.pop();
• Reading the number of elements (array length):
arr.length;
• Finding element's index in the array:
arr.indexOf(1);
27
Example
• You can also declare arrays with variable length.
• arrayName = new Array();
• Length = 0, allows automatic extension of the length.
• Car[9] = “Ford”; Car[99] = “Honda”;
<script language=“JavaScript”>
Car = new Array(3);
Car[0] = “Ford”;
Car[1] = “Toyota”;
Car[2] = “Honda”;
document.write(Car[0] + “<br>”);
document.write(Car[1] + “<br>”);
document.write(Car[2] + “<br>”);
</script>
28
variable that has not been defined or you have declared but you
forgot to provide with a value
• Null refers to “nothing”
Example
<html>
<head>
<title> Null and Undefined example </title>
<script language=“JavaScript”>
var test1, test2 = null;
alert(“No value assigned to the variable” + test1);
alert(“A null value was assigned” + test2);
</script>
</head>
<body> … </body>
</html>
30
Expressions
• It is a set of literals, variables, operators that merge and evaluate
to a single value
expressions.
• Arithmetic, logical
Operators
• Arithmetic operators
• Logical operators
• Comparison operators
• String operators
• Bit-wise operators
• Assignment operators
• Conditional operators
32
Unary operators
• Unary type operators take only one operand
• Which one add value first, and then assign value to the variable?
Name Example
Logical operators
• Used to perform Boolean operations on Boolean operands
&& Logical and Evaluate to “true” when both 3>2 && 5<2
operands are true
Comparison Operators
• Used to compare two numerical values
Operator Name Description Example
== Equal Perform type conversion before checking the “5” == 5
equality
< Less than “true” if left operand is less than right operand 3<5
>= Greater than or “true” if left operand is greater than or equal to the 5 >= 2
equal right operand
<= Less than or equal “true” if left operand is less than or equal to the right 5 <= 2
operand
35
String Operators
• JavaScript only supports one string operator for joining two
strings.
Operator Name Description Return
value
+ String Joins two strings “HelloWorld
concatenation ”
<script language=“JavaScript”>
var myString = “”;
myString = “Hello” + “World”;
alert(myString);
</script>
36
Example
• The + operator joins strings
• What is "9" + 9?
alert("9" + 9); // 99
alert(parseInt("9") + 9); // 18
37
Assignment Operators
• Used to assign values to variables
JavaScript Comments
• JavaScript comments can be used to explain JavaScript code, and to make it
more readable.
• JavaScript comments can also be used to prevent execution, when testing
alternative code.
• Comments are ignored, and will not be executed
• Example:
Thank You
Conditional Statements
• Conditional statements are used to perform different actions
If statement
• Use the if statement to specify a block of JavaScript code to be
executed if a condition is true
• Syntax:
if (condition)
{
block of code to be executed if the condition is true
}
else statement
• Use the else statement to specify a block of code to be executed
if the condition is false.
• Syntax:
if (condition) {
block of code to be executed if the condition is true
}
else {
block of code to be executed if the condition is false
}
• Example: if (hour<6){
greeting=“good morning”;
}
else{
greeting=“good afternoon”;
}
43
else if statement
• Use the else if statement to specify a new condition if the first
condition is false.
• Syntax:
if (condition1)
{
block of code to be executed if the condition1 is true
}
else if(condition2)
{
block of code to be executed if the condition2 is true
}
else{
block of code to be executed if both of the conditions are false
}
44
else if statement
• Example: If time is less than 6:00, create a "Good morning"
if (hour<6){
greeting=“good morning”;
}
else if(hour<12{
greeting=“good afternoon”;
}
else{
greeting=“good evening”;
}
45
switch statement
• Use the switch statement to select one of many blocks of code
to be executed..
• Syntax:
switch(expression){
case n:
code block
break;
case n:
code block
break;
default:
default code block
}
NB: The default specifies the code to run if there is no case match.
46
switch statement
This is how it works:
• The switch expression is evaluated once.
• The value of the expression is compared with the values of each
case.
• If there is a match, the associated block of code is executed.
case 3:
Example: day = "Wednesday";
switch (new Date().getDay()) { break;
case 0: case 4:
day = "Sunday"; day = "Thursday";
break; break;
case 1: case 5:
day = "Monday"; day = "Friday";
break; break;
case 2: case 6:
day = "Tuesday"; day = "Saturday";
break; break;
}
47
Loop/iteration statement
condition is true
For loop
• Loops can execute a block of code a number of times
• Syntax:
For/in loop
• The JavaScript for/in statement loops through the properties of
an object.
for (counter-variable in Object) {
• Syntax: statements;
}
• Example:
while loop
• Execute a block of code as long as a specified condition is
true.
• Syntax:
while (condition)
{
block of code to be executed if the condition is true
Increment/decrement statement;
}
• Example:
while (i < 10)
{
text += "The number is " + i;
i++;
}
51
Do…while loop
• This loop will execute the code block once, before checking the
condition, then it will repeat the loop as long as the condition is
true.
• Syntax: do{
block of code to be executed
Increment/decrement statement;
}
while (condition);
• Example:
do{
text += "The number is " + i;
i++;
}
while(i<10);
52
Exercises
• For loop
• Write a JavaScript program to count up from 1 -->10
• Write a JavaScript program to count down from 10 -->1
• For/in loop
• Write a JavaScript program to display student information
• Write a JavaScript program to display 4 Ethiopian languages
• While loop
• Write a JavaScript program to count up from 1 -->10
• Write a JavaScript program to count down from 10 -->1
• Do-while loop
• Write a JavaScript program to count up from 1 -->10
• Write a JavaScript program to count down from 10 -->1
53
Functions
• A function is a block of organized reusable code (a set of
Built-in functions
• Functions provided by the language and you cannot change
them to suit your needs.
• Some of the built-in functions in JavaScript are shown here:
• eval - eval(expr)
• eval evaluates the expression or statements
• isFinite
• Determines if a number is finite
• isNaN
• Determines whether a value is “Not a Number”
• parseInt
• Converts string literals to integers, no number → NaN.
• parseFloat
• Finds a floating-point value at the beginning of a string.
55
User-defined functions
• For some functionality, you cannot achieve by only using the
built-in functions.
• You can define your own function as follows
Exercises
using function
• Write a JavaScript program to convert Celsius into
Events
• are actions that occur as a result of browser activities or user
interactions with the web pages, such as
• user performs an action (mouse click or enters data)
• validate the data entered by a user in a web form
• Communicate with Java applets and browser plug-ins
• Event categories
• Keyboard and mouse events
• Load events
• Form-related events
• onFocus() refers to placing the cursor into the text
input in the form.
• Others
• Errors, window resizing.
59
Event handlers
they handle
• Example:
<html>
<head>
<title>onLoad and onUnload Event Handler </title>
</head>
<body onLoad=“alert(‘Welcome User’);”
onUnload=“alert(‘Thanks for visiting the page’);”>
Load and UnLoad event test.
</body>
</html>
64
user input.
• Radio buttons
• Hidden fields
• Password fields
Example
<head>
<script LANGUAGE="JavaScript">
function checkForm( )
{
if (document.mainForm.firstName.value == "") {
alert("Please type in your first name!");
}
}
</script>
</head>
<h3> Form Validation</h3>
<form name="mainForm" onsubmit="return checkForm()">
Name: <input type="text" name="firstName" />
<p><input type="submit" value="Submit"></p>
</form>
69
// -->
</script></head>
<body><h1>On-Line Training</h1>
<form action="cgi-bin/registerLanguage" name="langForm">
To see an introduction to any of our on-line training
courses, please enter the name of an important Web
programming language below.
<p>
<b>Language:</b>
<input type=“text" name="langField"
onFocus="describeLanguage()" onBlur="clearStatus()"
onChange="checkLanguage()">
<p>
<input type=“submit" value="Show It To Me">
</form>
</body></html>
72
Result
73
Example: 2
<html>
<head>
<script type="text/javascript">
// Form validation code will come here.
function validate() <body >
{ <form method='post' name="Form1"
if( document.Form1.username.value == "" ) onsubmit="return(validate())"; >
{ <fieldset>
alert( "Please provide your username!" ); <legend> <b>Login form</b></legend>
document.Form1.username.focus() ; Username:
return false; <input type="text" name="username"
} maxlength="50" size="25"><br><br>
if( document.Form1.password.value == "" ) Password:
{ <input type="password" name="password"
alert( "Please provide your password!" ); maxlength="50" size="25"><br/><br>
document.Form1.password.focus() ; <input type='submit' value="login" /><input
return false; type='reset' value='Reset' />
} </fieldset>
} </form>
</script> </body>
</head>
</html>
74
]\d{4}$/;
the browser.
?
END OF CHAPTER FOUR
Next: Chapter Five – PHP