Week 6
Week 6
JUNIOR HIGH
SCHOOL-G8
Programming
Using Web
Technology
Quarter 3 – Module 6
WEEK 6
1
5 - JavaScript
What is JavaScript?
HTML and CSS concentrate on a static rendering of a page; things do not change on the page over
time, or because of events.
To do these things, we use scripting languages, which allow content to change dynamically.
Not only this, but it is possible to interact with the user beyond what is possible with HTML.
Scripts are programs just like any other programming language; they can execute on the client side
or the server.
2
5 - JavaScript
A user's request is fulfilled by running a script directly on the web server to generate dynamic HTML
pages.
This HTML is then sent to the client browser.
It is usually used to provide interactive web sites that interface to databases or other data stores on
the server.
3
5 - JavaScript
This is different from client-side scripting where scripts are run by the viewing web browser, usually
in JavaScript.
The primary advantage to server-side scripting is the ability to highly customize the response based
on the user's requirements, access rights, or queries into data stores.
Embedded JavaScript
JavaScript can be embedded in an HTML document.
To embed it in HTML you must write:
<script type=”text/javascript”>
</script>
The script tag has effect of the stopping the JavaScript being printed out as well as indentifying the
code enclosed.
The JavaScript can be placed in the head section of your HTML or the body.
<html>
<body>
<script type=”text/javascript”>
document.write("<h1>This is a heading</h1>");
</script>
</body>
</html>
The Scripts placed in the body section are executed as the page loads and can be used to generate
the content of the page.
As well as the body section, JavaScript can also be placed in the head part.
The advantages of putting a script in there are that it loads before the main body.
External JavaScript
If you want to use the same script on several pages it could be a good idea to place the code in a
separate file, rather than writing it on each.
4
5 - JavaScript
That way if you want to update the code, or change it, you only need to do it once.
5
5 - JavaScript
Simply take the code you want in a separate file out of your program and save it with the extension
.js.
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
JavaScript Variables
Variables in JavaScript behave the same as variables in most popular programming languages (C,
C++, etc) do, but in JavaScript you don't have to declare variables before you use them.
A variable's purpose is to store information so that it can be used later. A variable is a symbolic name
that represents some data that you set.
When using a variable for the first time it is not necessary to use "var" before the variable name.
Variable names must begin with a letter.
Variable names are case sensitive (y and Y are different variables).
var x=5;
var y=6;
var z=x+y;
You can declare many variables in one statement. Just start the statement with var and separate the
variables by comma:
var name="Doe", age=30, job="carpenter";
var name="Doe",
age=30,
job="carpenter";
JavaScript Operators
Operators in JavaScript are very similar to operators that appear in other programming languages.
The definition of an operator is a symbol that is used to perform an operation.
Most often these operations are arithmetic (addition, subtraction, etc), but not always.
6
5 - JavaScript
Operator Name
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
= Assignment
<body>
<script type="text/JavaScript">
<!--
var two = 2
var ten = 10
varlinebreak = "<br />"
document.write("two plus ten = ")
var result = two + ten
document.write(result)
//-->
</script>
</body>
Assignment Equivalent to
X+=Y X=X+Y
X-=Y X=X-Y
X*=Y X=X*Y
X/=Y X=X/Y
X%=Y X=X%Y
JavaScript Array
An array is a special variable, which can hold more than one value at a time.
The Array object is used to store multiple values in a single variable.
An array can be created in three ways.
The following code creates an Array object called myCars.
1. Regular
varmyCars=new
Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
2. Condensed
varmyCars=new Array("Saab","Volvo","BMW");
7
5 - JavaScript
3. Literal
8
5 - JavaScript
varmyCars=["Saab","Volvo","BMW"];
Access an Array
You refer to an element in an array by referring to the index number.
This statement access the value of the first element in myCars.
var name=myCars[0];
myCars[0]="Opel";
JavaScript Functions
A function is a section of code that is separate from the main program.
It is defined once but can be invoked many times.
A function can be passed as parameters so that they can be used and a value can be returned back.
There are some functions already built in to JavaScript, such as the Math.cos() function, which
calculates the cosine of an angle.
An example function could be:
functionmultByTen(x)
{
return x*10;
}
This can then be invoked by using the function’s name complete with any parameters you want to
pass:
mysum=multByTen(3)
<html><body>
<script type=”text/javascript”>
var z= multXbyY(10,15);
document.write(“The result is” +z);
functionmultXbyY(x,y) {
document.write(“x is ”
+x); document.write(“y is
”+y); return x*y;
}
</script>
</body></html>
9
5 - JavaScript
JavaScript Conditions
Conditional statements are used to perform different actions based on different conditions.
In JavaScript we have the following conditional statements:
o if statement - use this statement to execute some code only if a specified condition is true
o if...else statement - use this statement to execute some code if the condition is true and
another code if the condition is false
o if...else if....else statement - use this statement to select one of many blocks of code to be
executed
o switch statement - use this statement to select one of many blocks of code to be executed
If Statement
Use the if statement to execute some code only if a specified condition is true.
if (condition)
{
code to be executed if condition is true
}
If...else Statement
Use the if....else statement to execute some code if a condition is true and another code if the
condition is not true.
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
if (condition1) {
code to be executed if condition1 is true
}
else if (condition2) {
code to be executed if condition2 is true
}
else {
code to be executed if neither condition1 nor condition2 is true
10
5 - JavaScript
}
11
5 - JavaScript
Switch Statement
Use the switch statement to select one of many blocks of code to be executed.
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on some
condition.
variablename=(condition)?value1:value2
voteable=(age<18)?"Too young":"Old enough";
12
5 - JavaScript
var person={fname:"John",lname:"Doe",age:25};
for (x in person)
{
txt=txt + person[x];
}
while (condition)
{
code block to be executed
}
do
{
code block to be executed
}
while (condition);
13
5 - JavaScript
JavaScript Objects
JavaScript has several built-in objects, like String, Date, Array, and more.
An object is just a special kind of data, with properties and methods.
objectName.propertyName
This example uses the length property of the String object to find the length of a string:
objectName.methodName()
This example uses the toUpperCase() method of the String object, to convert a text to uppercase.
person=new Object();
person.firstname="Narendra";
person.lastname="Modi";
person.age=24;
person.eyecolor="blue";
14
5 - JavaScript
User- Defined Objects/How user defined objects are created in
JavaScript?
JavaScript allows you to create your own objects.
15
5 - JavaScript
The first step is to use the new operator.
VarmyObj= new Object();
This creates an empty object.
This can then be used to start a new object that you can then give new properties and methods.
In object- oriented programming such a new object is usually given a constructor to initialize values
when it is first created.
However, it is also possible to assign values when it is made with literal values.
<!DOCTYPE html>
<html>
<body>
</body>
</html>
16
5 - JavaScript
<!DOCTYPE html>
<html>
<body>
<script>
function person(firstname, lastname, age)
{
this.firstname =
firstname; this.lastname =
lastname; this. age = age;
}
var person1=new person("Narendra","Modi",24);
document.write(person1.firstname + “ ”+ person1.lastname +” “+ person1.age);
</script>
</body>
</html>
In above the function personbecomes the constructor invoked through the new keyword on
assignment to the person1 variable.
Here the values are passed as parameters to the constructor.
Inside the constructor the this keyword takes on the value of the newly created object and therefore
applies properties to it.
17
5 - JavaScript
head, html, iframe, isindex, meta, param,
script, style, title
onkeyup All elements except br, font, frame, frameset, a key was released
head, html, iframe, isindex, meta, param,
script, style, title
onload frameset all the frames have been loaded
onload body the document has been loaded
onmousedown All elements except br, font, frame, frameset, a pointer button was pressed
head, html, iframe, isindex, meta, param, down
script, style, title
onmousemove All elements except br, font, frame, frameset, a pointer was moved within.
head, html, iframe, isindex, meta, param,
script, style, title
onmouseout All elements except br, font, frame, frameset, a pointer was moved away
head, html, iframe, isindex, meta, param,
script, style, title
onmouseover All elements except br, font, frame, frameset, a pointer was moved onto
head, html, iframe, isindex, meta, param,
script, style, title
onmouseup All elements except br, font, frame, frameset, a pointer button was released
head, html, iframe, isindex, meta, param,
script, style, title
onreset form the form was reset
onselect input, textarea some text was selected
onsubmit form the form was submitted
onunload frameset all the frames have been
removed
onunload body the document has been removed
18
5 - JavaScript
<form name=”userDetails”>
<input type=”text” name= “ fname“/>
<input type=”text” name= “lname“/>
<input type=”submit” name= “ Submit“/>
The form data can then be accessed with various DOM syntax constructions. The form itself can be
accessed through:
document.forms[0];
<script
type="text/javascript">
functionincrementCurrent() {
current = parseInt(document.forms["noteForm"].total.value);
document.forms["noteForm"].total.value = current + 1;
}
</script>
</head><body>
<div id="mainDiv">
<h1>Document Object Example</h1>
<form id="noteForm">
Current number of notes:
<input type="text" name="total" value="0" size="3"/>
<input type="button" value="Add a new note"
onclick="incrementCurrent()"/>
</form>
</div>
</body></html>
19
5 - JavaScript
The idea behind JavaScript form validation is to provide a method to check the user
enteredinformation before they can even submit it.
JavaScript also lets you display helpful alerts to inform the user what information they have entered
incorrectly and how they can fix it.
<html>
<head>
<title>JavaScript Forms</title>
</head>
<body>
<form method=”post” name=”getinfo” onSubmit=”return processForm()”>
<input type=”text” name=”email”/>
<input type=”submit” value=”log in” name=”Login”/>
</form>
20
5 - JavaScript
</html>
21
5 - JavaScript
The way it determines this end result is built on the template/pattern in the string emailpattern.
This is used to work out the order of expected characters, how many times they repeat and specially
occurring punctuation.
The string in this case that is used as template is:
“^*\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w+$”
The first section is:
^[\\w-_\.]
This sequence, beginning with ^, means check the first character is a word character represented by
\\w.
The next part is :
*[\\w-_\.]
The * means that the next series of characters described can be represented many times or not at
all.
The characters themselves are the same as before; that is word characters, underscore, hyphen or
period.
\@[\\w]\.+
[\\w]+[\\w]$
The first set in square brackets makes sure that there are some characters after the dot and the last
part checks that the last character is a word character.
In this program after the string is declared, a regular expression object is created with the pattern:
var regex = new RegExp(emailpattern);
The pattern can then be tested against the incoming parameter with object’s test method:
returnregex.test(chkMail);
This will return true or false depending on whether there is a match or not.
22
5 - JavaScript
23
5 - JavaScript
• JS Array
• JS Boolean
• JS Math
• JS RegExp
var x=Math.PI;
var y=Math.sqrt(16);
24
5 - JavaScript
25