0% found this document useful (0 votes)
13 views32 pages

IP Chapter 4 JS

Uploaded by

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

IP Chapter 4 JS

Uploaded by

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

Web programming

CHAPTER 4: 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 JavaScript programs 9
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.

10
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);
}
//-->
</script
11
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

12
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:
– Example: let x1 = 34.00; 13
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"];
let car = cars[0]; 14
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.

15
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>

16
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
elements).
17
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
– Automatically (self invoked)
18
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>

19
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");

20
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).
21
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";
}

22
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>
23
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> 24
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");

25
JavaScript - Dialog Boxes…
– Example:
<!DOCTYPE html>
<html><body>
<h1>The Window Object</h1>
<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>
</body></html>
26
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.

27
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>

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

29
JavaScript Form Validation…
Example: <DOCTYPE html >
<html> <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> 30
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>

31
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?

32

You might also like