Chapter 3 Javascript
Chapter 3 Javascript
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>
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…
15
JavaScript Operators…
20
JavaScript Arrays…
21
JavaScript Arrays…
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) {
} 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:
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
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…
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