0% found this document useful (0 votes)
16 views86 pages

Ch4 WP

notetype

Uploaded by

Mesfin Tadesse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views86 pages

Ch4 WP

notetype

Uploaded by

Mesfin Tadesse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 86

Chapter four

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.

•Simplicity - JavaScript's syntax was inspired by Java's and is


relatively easy to learn compared to other popular languages like
C++. 6
Cont..
•Interoperability - Unlike PHP or other scripting languages,
JavaScript can be inserted into any web page. JavaScript can be
used in many different kinds of applications because of support
in other languages like Pearl and PHP.

•Server Load - JavaScript is client-side, so it reduces the demand


on servers overall, and simple applications may not need a server
at all.

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…

<script language="javascript" type="text/javascript>

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

 It is possible to create a variable with or without the var


statement
var strname = some value or var a= 5;
strname = some value or a=5;
 JavaScript is untyped language. This means that a JavaScript
variable can hold a value of any data type.

25
Cont…
 You should not use any of the JavaScript reserved keywords as

a variable name.

 JavaScript variable names should not start with a numeral (0-

9). They must begin with a letter or an underscore character.


For example:

 123test is an invalid variable name but _123test is a valid

 Name and name are two different variables. (case sensitive)

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

Arithmetic operators +, -, *, /, % , ++ and --

Assignment operators =, +=, -=, *=, /= and %=

Comparison operators ==,


= = =,
!=, >, <, >= and <=

Conditional operator ?:

Logical operators &&, || and !

Bitwise operators & (and),| (or), ^ (xor), ~ (not),


>>,

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…

• Logical operators example:

var x=60, var y=90

(var x<=100 && var y>= 10)

Returns: true

37
JavaScript if...else Statements

 JavaScript supports conditional statements which are used


to perform different actions based on different conditions.
 if statement:
 The if statement is the fundamental control statement that allows
JavaScript to make decisions and execute statements conditionally.
if (expression)
{
Statement(s) to be executed if expression is true
}

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

following three important parts:


 The loop initialization where we initialize our counter to a starting

value. The initialization statement is executed before the loop begins.


 The test statement which will test if the given condition is true or not.

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)

Statement(s) to be executed if test


condition is true

}
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.

 A JavaScript function is executed only by an event or by a call to that function.

 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

pages if the function is embedded in an external .js file).

 Functions can be defined either <head> or <body> section

 As a convention, they are typically defined in the <head> section

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.

• If the function was invoked from a statement, JavaScript will


"return" to execute the code after the invoking statement.

• Functions often compute a return value. The return value is


"returned" back to the "caller":

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.

• The innerHTML property can be used to get or change any


HTML element, including <html> and <body>.

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>

<h2>JavaScript HTML DOM</h2>

<p>Finding HTML Elements by Tag Name.</p>


<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>

<p id="demo"></p>
<script>
const element = document.getElementsByTagName("p");

document.getElementById("demo").innerHTML = 'The text in first paragraph (index 0) is: '


+ element[0].innerHTML;
</script>
</body> 63
</html>
JavaScript HTML DOM - Changing
CSS

• The HTML DOM allows JavaScript to change the style of


HTML elements.

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>

<img id="myImage" src="smiley.gif">

<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

document.images Returns all <img> 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

 A web page or an image loading

 Mousing over a hot spot on the web page

 Selecting an input box in an HTML form

 When the user clicks a button (Submitting an HTML form)

 pressing any key,

 closing window,

 resizing window etc. 67


Cont…
 Attributes are inserted into HTML tags to define events and
event handlers
 With single quotes:

<some-HTML-element some-event='some JavaScript'>


 With double quotes:

<some-HTML-element some-event="some JavaScript">

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>

Enter your name: <input type="text" id="fname" onchange="myFunction()">

<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

<form name="contact_form" onsubmit=“return validate_form ( );">


<h1>Please Enter Your Name</h1>
<p>Your Name: <input type="text" name="contact_name"></p>
<p><input type="submit" name="send" value="Send Details"></p>
</form>

75
Cont…
 The first part of the form is the form tag:

 The form is given a name of "contact_form". This is so that we can


reference the form by name from our JavaScript validation function.
 The form tag includes an onsubmit attribute to call our JavaScript
validation function, validate_form(), when the submit type of button
in the form is pressed.
 The function validate_form() will validate whether the user enters
Name or not.

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

You might also like