0% found this document useful (0 votes)
22 views44 pages

Chapter 3 Javascript

Chapter 3 of the document provides an overview of JavaScript, a lightweight programming language used for adding interactivity to websites. It covers JavaScript syntax, variables, data types, functions, conditional statements, and loops, along with examples of how to implement them in web pages. The chapter emphasizes the integration of JavaScript with HTML and its role in creating dynamic web applications.

Uploaded by

eyibeltal3939
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)
22 views44 pages

Chapter 3 Javascript

Chapter 3 of the document provides an overview of JavaScript, a lightweight programming language used for adding interactivity to websites. It covers JavaScript syntax, variables, data types, functions, conditional statements, and loops, along with examples of how to implement them in web pages. The chapter emphasizes the integration of JavaScript with HTML and its role in creating dynamic web applications.

Uploaded by

eyibeltal3939
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/ 44

Internet programming

CHAPTER 3: JAVASCRIPT
What is JavaScript?
• A script is a small piece of program that can add
interactivity to your website.
• For example, a script could generate a pop-up
alert box message, or provide a dropdown menu.
• This script could be written using JavaScript or
VBScript.
• Javascript can be used in two ways:External
JavaScript and Internal JavaScript.
• To include a JavaScript library or script file in your web page,
use this syntax:
<script type="text/javascript"src="somejavascript.js"></script>
2
Cont’d
• JavaScript is a lightweight, interpreted programming
language.
• It is designed for creating network-centric applications.
• It is complementary to and integrated with Java.
• It is complementary to and integrated with HTML.
• It is open and cross-platform

3
What can you do with JavaScript?
• Validate form fields
• Dynamically alter the appearance of a page
element
• Hide and show elements
• Move elements about the page
• Capture user events and adjust the page
accordingly
• Interface with a server-side application without
leaving the page
• Set and retrieve web cookies
4
JavaScript Syntax
• JavaScript can be implemented using JavaScript
statements that are placed within the <script>...
</script> HTML tags in a web page.
• Syntax:
<script language = "javascript" type = "text/javascript">
JavaScript code goes here…..
</script>

• The script tag takes two important attributes:


– Language: specifies what scripting language you are using.
– Type: is what is now recommended to indicate the
scripting language in use.
• NB: JavaScript is a case-sensitive language 5
Cont’d
• First JavaScript Code example:
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
• NB: A function document.write is used to write a string into our
HTML document.
6
JavaScript code Location
• Place the JavaScript in the <body> section:
– When the JavaScript dynamically creates web page content as
the page is being loaded.
• Place the JavaScript in the <head> section:
– When the JavaScript defined in functions and used for page
events, as this is loaded before the body.
• You can also put your JavaScript code in <head>
and <body> section.

7
JavaScript code Location…
• JavaScript code in the body section example:
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html> 8
JavaScript code Location…
• JavaScript code in the head section example:
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
Click here for the result
<input type="button" onclick="sayHello()" value="Say
Hello" />
</body>
</html>
• NB: JavaScript ignores spaces, tabs, and newlines that appear in
9
JavaScript programs
JavaScript Comments
• 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.
• Example:
<script language = "javascript" type = "text/javascript">
<!--
// This is a single line comment.
/*
* This is a multi-line comment in JavaScript
* It is very similar to comments in C Programming
10
*/
JavaScript Variables
• Variables are containers for storing data
(storing data values).
• We can declare a JavaScript Variable in four
ways:
– Using var: example: var x = 5;
– Using let: example: let x = 5;
– Using const: example: const price1 = 5;
– Using nothing: example: x = 5;
• The let and const keywords were added to JavaScript in 2015.
• If you want your code to run in older browser, you must use var.

11
JavaScript Variable Scope
• A global variable has global scope which means it can
be defined anywhere in your JavaScript code.
• A local variable will be visible only within a function
where it is defined.
– Function parameters are always local to that function.
• Example:
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
12
</script
JavaScript Identifiers
• The general rules for constructing names for
variables (unique identifiers) are:
– Names can contain letters, digits, underscores, and
dollar signs.
– Names must begin with a letter
– Names can also begin with $ and _
– Names are case sensitive (y and Y are different
variables)
– Reserved words (like JavaScript keywords) cannot be
used as names

13
JavaScript Operators
• The assignment operator (=) assigns a value to a
variable.
– Example: let x = 10;
• The arithmetic operators are used to perform
arithmetic on numbers.
– The arithmetic operators are addition, subtraction,
multiplication, division, modules, increment and
decrement.
• The + operator can also be used to add
(concatenate) strings.
– Example:
let text1 = "What a very ";
14
text1 += "nice day";
JavaScript Operators…

• JavaScript Comparison Operators

15
JavaScript Operators…

• JavaScript Logical Operators

• JavaScript Type Operators

 used to check the type of an object at the run time.


 It returns a boolean value(true or false)
16
JavaScript Data Types
• JavaScript variables can hold different data types
• JavaScript have the following data types:
• JavaScript Strings
– A string (or a text string) is a series of characters like
"John ".
– Strings are written with quotes. You can use single or
double quotes:
– Example: let answer1 = 'He is called "Johnny"';
• JavaScript Numbers
– JavaScript has only one type of numbers.
– Numbers can be written with, or without decimals:
17
– Example: let x1 = 34.00;
JavaScript Data Types…
• JavaScript Booleans
– Booleans can only have two values: true or false.
– Example: let x = 5;
let y = 5;
(x == y) //// Returns true
• JavaScript Objects
– JavaScript objects are written with curly braces {}.
– Object properties are written as name:value pairs,
separated by commas.
– Example:
const person = {firstName:"John",
lastName:"Doe", age:50, eyeColor:"blue"};
18
JavaScript Arrays
• An array is a special variable, which can hold more
than one value.
• Creating an Array
– Using an array literal is the easiest way to create a
JavaScript Array.
– Syntax: const array_name = [item1, item2, ...];
• Accessing Array Elements
– You can access an array element by referring to the
index number.
– Example:
const cars = ["Saab","Volvo","BMW"];
19
let car = cars[0];
JavaScript Arrays…
• Access the Full Array
– With JavaScript, the full array can be accessed by
referring to the array name:
– Example:
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
• The innerHTML property sets or returns the HTML content (inner HTML) of an
element.

20
JavaScript Arrays…

• Arrays are Objects


– Arrays are a special type of objects.
– Objects use names to access its "members".
– Example:
<p id="demo"></p>
<script>
const person = {firstName:"John", lastName:"Doe",
age:46};
document.getElementById("demo").innerHTML =
person.firstName;
</script>

21
JavaScript Arrays…

• JavaScript Array Methods


– JavaScript Arrays have the following methods:
– toString(): converts an array to a string of (comma
separated) array values.
– sort(): Sorts the array
– indexOf() Returns the first (least) index of an element
within the array equal to the specified value, or -1 if
none is found.
– push() Adds one or more elements to the end of an
array and returns the new length of the array
• The array length Property
– returns the length of an array (the number of array
22
elements).
JavaScript Functions
• A JavaScript function is a block of code designed to
perform a particular task.
• A JavaScript function is executed when "something"
invokes it (calls it).
• Syntax:
function name(parameter1, parameter2, parameter3){
// code to be executed
}

• 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
23
– Automatically (self invoked)
JavaScript Functions…
• When JavaScript reaches a return statement, the
function will stop executing.
• Example:
<p id=“demo”></p>
<script>
let x = myFunction(4, 3); // Function is called, return value will end up in x
document.getElementById("demo").innerHTML =x;
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
</script>

24
JavaScript Date Objects
• By default, JavaScript will use the browser's time
zone and display a date as a full text string.
• Date objects are created with the new Date()
constructor.
• There are different ways to create a new date
object:
– new Date(): example: const d = new Date();
– new Date(year, month, day, hours, minutes, seconds, milliseconds): example:
const d = new Date(2018, 11, 24, 10, 33, 30, 0);
– new Date(date string):
example: const d = new Date("October 13, 2014 11:13:00");

25
JavaScript Math Object
• The JavaScript Math object allows you to perform mathematical tasks on
numbers.
• Math Properties (Constants):
– The syntax for any Math property is : Math.property.
– Example: Math.PI // returns PI
• Math Methods:
– The syntax for any Math methods is : Math.method(number)
– Example:
• Math.round(x) Returns x rounded to its nearest integer
• Math.trunc(x) Returns the integer part of x
• Math.sign(x) returns if x is negative, null or positive:
• Math.pow(x, y) returns the value of x to the power of y:
• Math.sqrt(x) returns the square root of x:
• Math.sin(x) returns the sine (a value between -1 and 1) of the angle x
(given in radians).
26
JavaScript Conditional Statements
• In JavaScript we have the following conditional statements:
• The 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
}
Example:
<p id=“demo”> Good Evening!</p>
<script>
if (new date().getHours ()< 18) {

document.getElementById("demo").innerHTML =“Good Day”;

greeting = "Good day";

} 27
JavaScript Conditional Statements…
• The 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:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if</h2>
<p>Display "Good Afternoon!" if the hour is less than 18:00:</p>
<p id="demo">Good Morning!</p>
<script>
if (new Date().getHours() < 18) {
document.getElementById("demo").innerHTML = "Good Afternoon!";}
</script>
</body>
</html> 28
JavaScript Conditional Statements…
• The 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 condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
– Example:
<!DOCTYPE html>
<html><body>
<h2>JavaScript if .. else</h2>
<p>A time-based greeting:</p>
<p id="demo"></p>
<script>
const hour = new Date().getHours();
let greeting;
if (hour < 6) {
greeting = "Good day";
} else {
greeting = "Good evening"; }
document.getElementById("demo").innerHTML = greeting;
</script> 29
</body></html>
JavaScript Conditional Statements…
• The JavaScript Switch Statement
– Use the switch statement to select one of many code
blocks to be executed.
– Syntax:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

30
JavaScript Conditional Statements…
Example:
The getDay() method returns the weekday as a number between 0 and 6.
(Sunday=0, Monday=1, Tuesday=2 ..)
This example uses the weekday number to calculate the weekday name:

<!DOCTYPE html> case 3:


<html><body> day = "Wednesday";
<h2>JavaScript switch</h2> break;
<p id="demo"></p> case 4:
<script> day = "Thursday";
let day; break;
switch (new Date().getDay()) { case 5:
case 0: day = "Friday";
day = "Sunday"; break;
break; case 6:
case 1: day = "Saturday";}
day = "Monday"; document.getElementById("demo").inner
break; HTML = "Today is " + day;
case 2: </script>
day = "Tuesday"; </body>
break; </html>
31
JavaScript Loop statements
• Loops can execute a block of code a number of times.
• JavaScript For Loop
– Syntax:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
– Example:
<body>
<h2>JavaScript For Loop</h2>
<p id="demo"></p>
<script>
const country = ["Ethiopia", "S.Koria", "Kenya", "Eritra", "Russia", "China"];
let text = "";
for (let i = 0; i < country.length; i++) {
text += country[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
32
</script>
JavaScript Loop statements…
• The While Loop
– The while loop loops through a block of code as long as a specified condition is true.
– Syntax:
while (condition) {
// code block to be executed
}
– Example:
<h2>JavaScript While Loop</h2>
<p id="demo"></p>
<script>
let text = "";
let i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script> 33
JavaScript Loop statements…
• The Do While Loop
– The do while loop is a variant of the while loop.
– Syntax:
do {
// code block to be executed
}
while (condition);
– Example:
<!DOCTYPE html>
<html><body>
<h2>JavaScript Do While Loop</h2>
<p id="demo"></p>
<script>
let text = ""
let i = 0;
do {
text += "<br>The number is " + i;
i++; }
while (i < 10);
document.getElementById("demo").innerHTML = text;
34
</script>
JavaScript - Dialog Boxes
• JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt
box.
• Alert Box
– An alert box is often used if you want to make sure information comes
through to the user.
– When an alert box pops up, the user will have to click "OK" to proceed.
– Syntax:
window.alert("sometext");
– The window.alert() method can be written without the window prefix.
– Example:
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
35
JavaScript - Dialog Boxes…
• Confirm Box
– A 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 "Cancel" to proceed.
– Syntax:
window.confirm("sometext");

36
JavaScript - Dialog Boxes…
– Example:
<!DOCTYPE html>
<html><body>
<h1>The Window Object</h1>
<h2>The confirm() Method</h2>
<p>Click the button to display a confirm box.</p>
<button onclick="myFunction()">Display</button>
<p id="demo"></p>
<script>
function myFunction() {
let text;
if (confirm("Press a button!") == true) {
text = "You pressed OK!";
} else {
text = "You canceled!"; }
document.getElementById("demo").innerHTML = text; }
</script> 37
JavaScript - Dialog Boxes…
• Prompt Box
– A prompt box is often used if you want the user to
input a value before entering a page.
– When a prompt box pops up, the user will have to
click either "OK" or "Cancel" to proceed after
entering an input value.
– Syntax:
window.prompt("sometext","defaultText");
– The window.prompt() method can be written
without the window prefix.

38
JavaScript - Dialog Boxes…
• Example:
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
let text;
let person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello " + person + "! How are you today?";
}
document.getElementById("demo").innerHTML = text;
}
</script> 39
JavaScript Form Validation

• HTML form validation can be done by JavaScript.


• If a form field (fname) is empty, this function alerts a message,
and returns false, to prevent the form from being submitted.
• Basic Validation:
– the form must be checked to make sure all the mandatory
fields are filled in.
– It would require just a loop through each field in the form and
check for data.
• Data Format Validation:
– the data that is entered must be checked for correct form and
value.

40
JavaScript Form Validation…
Example:
<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()"
method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body> 41
JavaScript Form Validation…

• Automatic HTML Form Validation


– HTML form validation can be performed
automatically by the browser
– HTML Form Example:
<form action="/action_page.php" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>

42
JavaScript Form Validation…
• Data Validation
– Data validation is the process of ensuring that user
input is clean, correct, and useful.
– Typical validation tasks are:
• has the user filled in all required fields?
• has the user entered a valid date?
• has the user entered text in a numeric field?

43
Questions?

44

You might also like