Ch4 WP
Ch4 WP
JavaScript
Prepared by: Marta G. (MSc.)
2015 E.C.
1
Content
• Introduction to JavaScript
• Basic JavaScript Input Output
• JavaScript Comments
• JavaScript Data Types and Variables
• Arithmetic and Logical Operators in JavaScript
• Control Structures (Conditional and Looping Statements)
• Array in JavaScript
• JavaScript Functions
• JavaScript DOM (Document object Model)
• JavaScript BOM (Browser Object Model)
• Form Processing using JavaScript
2
JavaScript
• JavaScript was designed to add interactivity to HTML pages
• A JavaScript consists of lines of executable computer code
• JavaScript is an interpreted language
JavaScript code is usually embedded directly into HTML pages
JavaScript is a scripting language (a scripting language is a
lightweight programming language)
3
Cont…
JS is a lightweight programming language because
It has low memory usage,
It has low CPU usage,
Simple syntax and features,
and is incredibly easy to implement.
lightweight programming language does not consume a lot of
your CPU’s resources. It doesn’t put excess strain on your CPU
or RAM.
JS runs predominantly in the browser even though it has complex
paradigms and logic which means it uses fewer resources than
other languages.
4
Reading Assignment
• what are the similarities and differences between
scripting language, programming language and
markup language.
5
Advantages of
JavaScript
•Speed - JavaScript tends to be very fast because it is often run
immediately within the client's browser. So long as it doesn't
require outside resources, JavaScript isn't slowed down by calls to
a backend server. Also, major browsers all support JIT (just in
time) compilation for JavaScript, meaning that there's no need to
compile the code before running it.
7
Cont…
•Versatility - There are many ways to use JavaScript through
Node.js servers. If you were to bootstrap Node.js with Express,
use a document database like MongoDB, and use JavaScript on
the frontend for clients, it is possible to develop an entire
JavaScript app from front to back using only JavaScript.
8
Cont…
Increased interactivity: You can create interfaces
that react when the user hovers over them with a
mouse or activates them via the keyboard.
Richer interfaces: You can use JavaScript to include
such items as drag-and drop components and sliders
to give a Rich Interface to your site visitors.
9
Disadvantage
•Browser Support - While server-side scripts always produce
the same output, different browsers sometimes interpret
JavaScript code differently. These days the differences are
minimal, and you shouldn't have to worry about it as long as you
test your script in all major browsers.
10
JavaScript syntax
The JavaScript code can be written in the ‘html’
file or in the separate ‘JavaScript file (.js)’
JavaScript can be implemented using JavaScript
statements that are placed within the <script>...
</script> HTML tags in a web page.
11
Cont…
The script tag takes two important attributes:
• Language: This attribute specifies what scripting language
you are using. Typically, its value will be javascript.
• Type: is used to specify that the file type is text file and
contains javascript code and its value should be set to
“text/javascript”.
• Src: is used to specify the source JavaScript file
12
Cont…
JavaScript code
</script>
13
Cont…
• Semicolons are required if you want to put more than
one statement on a single line.
It is case sensitive language.
It is un typed language i.e. a variable can hold any
type of value.
o No need to declare type (int, bool, etc)
o Doesn't care about type until called
14
Cont…
Scripts can be placed:
In <head>...</head> section
In <body>...</body> section
In <body>...</body> and <head>...</head> sections.
In an external file with .js extension (To reuse identical
JavaScript code on multiple pages of a site). Here src
attribute of <script> tag is used.
15
Cont…
Syntax:
<html>
<head>
<script type="text/javascript">
...
</script>
</head>
<body>
<script type="text/javascript">
...
</script>
</body>
</html>
16
JS output methods
Method Description
Document.write() Display data in browser display
area.
innerHTML Display data in HTML element.
17
Cont…
Eg.: document.write
<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
18
Cont…
Eg.: innerHTML
<!DOCTYPE html>
<html>
<body>
<h1>my first JavaScript page </h1>
<p>my first paragraph</p>
<p id="demo"></p>
<script type="text/javascript">
document.getElementById('demo').innerHTML= 5+6;
</script>
</body>
</html>
19
Js popup boxes
• Alert box
An alert dialog box is mostly used to give a warning message to
the users.
When an alert box pops up, the user will have to click “ok” to
proceed.
Window.alert(“some text”) or alert(“some text”)
Eg: alert(“warning message”)
Confirm box
Is often used if you want the user to verify or accept something
When a confirm box pops up, the user will have to click either
“ok” or “cancle” to proceed.
Window.confirm(“sometext”) or confirm(“sometext”)
Eg: confirm(“do you want to continue”)
20
Cont..
Prompt box
• Is often used if you want the user to input a value
before entering a page.
• When a prompt box pop up, the user will have to
click either “ok” or “cancle” to proceed after entering
an input value.
• Window.prompt(“sometext”.”defaulttext”)
• This method can also be written without the window
prefix.
• Eg: var person=prompt(“please enter ur
name”,”abebe”);
21
Cont…
Example 1: Example 2:
<html> <html>
<head> <head>
<title>JavaScript</title> <script type="text/javascript">
</head> function sayHello() {
<body> alert("Hello World") }
<script type="text/javascript"> </script>
document.write("Hello World </head>
from JavaScript!<br>"); <body>
</script> Click here for the result
</body> <input type="button" onclick="sayHello()"
</html> value="Say Hello“ />
</body> </html>
22
Manipulating HTML Elements
To access an HTML element from JavaScript, you can use the document.getElementById(id) method.
Use the id attribute to identify the HTML element, and innerHTML to refer to the element content (to display data
in html element):
Example:
<html>
<body>
<h1>My First Web Page</h1>
<p id="demo">my first paragraph</p>
<script>
document.getElementById("demo").innerHTML =
"Paragraph changed.";
</script>
</body>
</html>
23
Comment in java
script
• JavaScript supports both C-style and C++-style
comments. Thus:
Any text between a // and the end of a line is
treated as a comment and is ignored by
JavaScript.
Any text between the characters /* and */ is
treated as a comment. This may span multiple
lines.
24
JavaScript Variables
25
Cont…
You should not use any of the JavaScript reserved keywords as
a variable name.
26
Java script variable scope
The scope of a variable is the region of your program in which it is
defined. JavaScript variables have only two scopes.
Global Variables: A global variable has global scope which
means it can be defined anywhere in your JavaScript code.
Local Variables: A local variable will be visible only within a
function where it is defined. Function parameters are always
local to that function.
27
Cont…
The lifetime of variables starts when they are declared,
and deleted when the page is closed or when the
function is completed .
28
Example of variable scope
<script type="text/javascript">
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
</script>
29
JavaScript operators
Type Operators
Conditional operator ?:
30
Example
<html>
<body> document.write("a + b + c = ");
<script type="text/javascript"> result = a + b + c;
var a = 33; document.write(result);
document.write(linebreak);
var b = 10;
var c = "Test"; a = a++;
var linebreak = "<br />"; document.write("a++ = ");
document.write("a + b = "); result = a++;
result = a + b; document.write(result);
document.write(result); document.write(linebreak);
b = b--;
document.write(linebreak);
document.write("b-- = ");
document.write("a - b = "); result = b--;
result = a - b; document.write(result);
document.write(result); document.write(linebreak);
document.write(linebreak); //-->
document.write("a / b = "); </script>
result = a / b;
<p>Set the variables to different
document.write(result);
values and then try...</p>
document.write(linebreak);
</body>
document.write("a % b = ");
</html>
result = a % b;
document.write(result);
document.write(linebreak); 31
Eg:
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var y = 0;
Var x = 5;
x++;
y=++x+10;
y++;
document.write(x--)
document.write(",")
document.write(++y)
</script>
</body>
32
</html>
Cont…
• Output :
33
Cont…
Comparison operators Eg:.
Var x=8; var z=“8” var k=8.0
x= = =z returns false.
x= = =k returns false.
x= =z returns true
34
Conditional Operator (? :)
• The conditional operator first evaluates an
expression for a true or false value and then executes
one of the two given statements depending upon the
result of the evaluation.
S.No Operator and Description
? : (Conditional )
1
If Condition is true? Then value X : Otherwise value Y
35
Cont’d…
• <html>
<body> document.write ("((a < b) ?
100 : 200) => ");
<script
result = (a < b) ? 100 : 200;
type="text/javascript"> document.write(result);
var a = 10; document.write(linebreak);
var b = 20; //-->
var linebreak = "<br />"; </script>
document.write ("((a > b) ? <p>Set the variables to
100 : 200) => "); different values and different
operators and then
result = (a > b) ? 100 : 200;
try...</p>
document.write(result); </body>
document.write(linebreak); </html>
36
Cont…
Returns: true
37
JavaScript if...else Statements
38
Cont’d…
<script type="text/javascript">
var age = 20;
if( age > 18 )
{
document.write("<b>Qualifies for driving</b>");
}
</script>
39
Cont’d…
if...else statement:
if (expression)
{
Statement(s) to be executed if expression is
true
}
else
{
Statement(s) to be executed if expression is
false
}
40
Cont’d…
<script type="text/javascript">
var age = 15;
if( age > 18 )
{
document.write("<b>Qualifies for driving</b>");
}
else
{
document.write("<b>Does not qualify for
driving</b>");
}
</script>
41
Cont’d…
if...else if... statement:
if (expression 1)
{
Statement(s) to be executed if expression 1 is true }
else if (expression 2)
{
Statement(s) to be executed if expression 2 is true
}
else if (expression 3)
{
Statement(s) to be executed if expression 3 is true
}
else
{
Statement(s) to be executed if no expression is true
} 42
Cont’d…
<script type="text/javascript"> else if( book == "economics" )
var book = "maths"; {
if( book == "history" ) document.write("<b>Economics
{ Book</b>");
document.write("<b>History
}
Book</b>");
else
}
{
else if( book == "maths" )
document.write("<b>Unknown Book</b>");
{
document.write("<b>Maths }
Book</b>"); </script>
}
43
JavaScript Switch Case
The basic syntax of the switch statement is to give an expression to evaluate
and several different statements to execute based on the value of the expression.
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
44
Cont’d…
<script case 'C':
type="text/javascript"> document.write("Passed<br />");
var grade='A'; break;
case 'D': document.write("Not so
document.write("Entering
good<br />");
switch block<br />");
break;
switch (grade) case 'F':
{ document.write("Failed<br />");
case 'A': break;
document.write("Good default:
job<br />"); document.write("Unknown
break; grade<br />")
}
case 'B':
document.write("Pretty document.write("Exiting switch
block");
good<br />");
</script>
break; 45
JavaScript for Loops
The for loop is the most compact form of looping and includes the
If condition is true then code given inside the loop will be executed
otherwise loop will come out.
The iteration statement where you can increase or decrease your
counter.
46
Cont…
You can put all the three parts in a single line
separated by a semicolon.
for (initialization; test condition; iteration statement)
}
47
Cont…
Eg:
<html>
<head>
<script type="text/javascript">
for(var i=5;i>=1;i--)
{
for(var j=1;j<=i;j++)
{
document.write("*")
}
document. Write('<br/>')
}
</script>
</head>
<body>
</body> 48
</html>
output
49
JavaScript Functions
• A function is a group of reusable code which can be called anywhere in your
program.
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce
different results.
You may call a function from anywhere within the page (or even from other
50
JavaScript Function Syntax
A JavaScript function is defined with the function keyword, followed by
a unique function name, followed by parentheses (), a list of parameters
(that might be empty), and a statement block surrounded by curly braces.
Function names can contain letters, digits, underscores, and dollar signs
(same rules as variables).
The parentheses may include parameter names separated by
commas: (parameter1, parameter2, ...)
51
Cont…
• Function parameters are listed inside the parentheses () in the
function definition.
• Function arguments are the values received by the function
when it is invoked.
• Inside the function, the arguments (the parameters) behave as
local variables.
52
Cont…
Syntax:
Function functionName(parameter1, parameter2, parameter3) {
code to be executed
}
53
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)
54
Function Return
• When JavaScript reaches a return statement, the function will
stop executing.
55
Cont…
To invoke a function somewhere later in the script, you would simple need to write
the name of that function as follows:
E.g. <html>
<head>
<script type="text/javascript">
function displaymessage() {
alert("Hello World!")
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!“ onclick="displaymessage()" >
</form>
</body>
</html> 56
Cont…
<script type="text/javascript">
sayHello();
</script>
<script type="text/javascript">
function sayHello(name, age)
{
alert( name + " is " + age + " years old.");
}
</script>
<script type="text/javascript">
sayHello('Zara', 7 );
</script
57
Cont…
<script type="text/javascript">
function increase(x){
x = x + 1;
document. Write( ‘Inside function x = ' . x .'<br />’)
}
x = 10;
increase(x);
document. Write( ‘Outside function x = ' . x .'<br />’)
</script>
Output:
58
Output
59
Cont…
• The innerHTML property is useful for getting or replacing the
content of HTML elements.
60
Cont…
• HTMLFormElement.reset() method to reset a form to its
initial state.
• document.getElementById('myform').reset();
61
Cont…
The document object represents the whole html
document.
When html document is loaded in the browser, it
becomes a document object. It is the root element that
represents the html document.
Methods of document object: We can access and change
the contents of document by its methods. Before all the
methods there is “document.”
62
Cont…
Example for getElementsByTagName
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const element = document.getElementsByTagName("p");
document.getElementById(id).style.property
= new style
document.getElementById("p2").style.color =
"blue";
64
HTML
The easiest way to modify the content of an HTML element is by using the innerHTML
property.
To change the value of an HTML attribute, use this syntax:
document.getElementById(id).attribute = new value
<!DOCTYPE html>
<html>
<body>
<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
</body>
</html>
In JavaScript, document.write() can be used to write directly to the HTML output stream:
65
• Finding HTML Objects
E.g.
document.forms Returns all <form> elements
66
Events in JavaScript
JavaScript's interaction with HTML is handled through events that
occur when the user or browser manipulates a page.
Example of events are like
Mouse click
closing window,
Example
<button onclick='getElementById("demo").innerHTML=Date()'>The time is?
</button>
68
Cont’d…
Event Value Description
onchange script Script runs when the element
changes
onsubmit script Script runs when the form is
submitted
onreset script Script runs when the form is reset
onselect script Script runs when the element is
selected
onblur script Script runs when the element loses
focus
onfocus script Script runs when the element gets
focus
onkeydown script Script runs when key is pressed
69
onkeypress script Script runs when key is pressed and
Cont’d…
onkeyup script Script runs when key is released
onclick script Script runs when a mouse click
ondblclick script Script runs when a mouse double-
click
onmousedown script Script runs when mouse button is
pressed
onmousemove script Script runs when mouse pointer
moves
onmouseout script Script runs when mouse pointer
moves out of an element
onmouseover script Script runs when mouse pointer
moves over an element
onmouseup script Script runs when mouse button is
released 70
example
<!DOCTYPE html>
<html>
<body>
<p>This example demonstrates how to assign an "onchange" event to an input
element.</p>
<p>When you leave the input field, a function is triggered which transforms the
input text to upper case.</p>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
71
</html>
Cont…
<html>
<head>
<script type="text/javascript">
function over()
{
document.getElementById('demo').style.color="red";
}
function out()
{
document.getElementById('demo').style.color="blue";
}
</script>
</head>
<body>
<div onmouseover="over()" onmouseout="out()">
<h2 id="demo"> This is inside the division </h2> </div>
</body>
</html> 72
Cont…
Special characters
you can place a backslash (\) before the double quotes and
other special characters
Code Outputs
\' single quote
\" double quote
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed
73
JavaScript - Form Validation
JavaScript, provides a way to validate form's data on
the client's computer before sending it to the web
server. Form validation generally performs two
functions.
Basic Validation - First of all, the form must be checked
to make sure data was entered into each form field that
required it. This would need just loop through each field
in the form and check for data.
Data Format Validation - Secondly, the data that is
entered must be checked for correct form and value. This
would need to put more logic to test correctness of data.
74
Cont…
The process of checking that a form has been filled in
correctly before it is processed.
Example: A simple form with validation
75
Cont…
The first part of the form is the form tag:
76
Validating text filed
Checks to see whether the text filed Is fill or not
Use built in function .value for validation
77
Cont…
Example:
<html>
<head>
<script>
function validateForm()
{
var x=document.myForm.fname.value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>
78
Cont…
<body>
<form name="myForm" onsubmit="return validateForm()"
method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
79
Validating radio buttons
Checks to see either of the radio buttons have been clicked.
Mostly used for unique identification
Use built in function .checked for validation
80
Cont…
Example:
<html>
<head>
<script>
function validation()
{
if ( ( document.reg_form.dept[0].checked == false ) &&
(document.reg_form.dept[1].checked == false) )
{ alert ( "Please choose your Gender: Male or
Female" );
valid = false;
}
}
</script>
</head>
81
Cont…
<body >
<form name="reg_form">
<input type="radio" name="dept" value="female">female
<input type="radio" name="dept" value="male">male
<input type="submit" onclick="validation()" value="register">
</form>
</body>
</html>
82
Validating drop-down lists
Used to make sure that one of the elements from drop down
list has been selected or not.
The pre defined function .selctedIndex can get the selected
element from the drop down list.
83
Cont…
Example:
<html>
<head>
<script>
function validation()
{
if ( document.reg_form.dept.selectedIndex == 0 )
{ alert ( "Please select your departement." );
return false;
}
}
</script>
</head>
84
Cont…
<body>
<form name="reg_form">
department<select name="dept">
<option>select your department here</option>
<option>computer science</option>
<option>information technology</option>
<option>information system</option>
</select>
<input type="button" value="register" onclick="validation()">
</body>
</html> 85
document.write(“Thank you!");
86