By The End of This Section of The Practical, The Students Should Be Able To
By The End of This Section of The Practical, The Students Should Be Able To
6 Introduction
JavaScript, which was originally named LiveScript, was developed by Netscape. LiveScript
became joint venture of Netscape and Sun Microsystems and its name was changed to JavaScript.
Microsoft’s JavaScript is named Jscript. The original goal of JavaScript was to provide
programming capability at both the server and the client ends of a Web connection. Server-side
JavaScript can serve as an alternative for some of what is done with server-side programming, in
which computational capability resides on the server and is requested by the client. On the other
hand, Client-side JavaScript cannot replace all server-side computing. It defines the collection of
objects, methods, and properties that allow scripts to interact with HTML documents on the client.
In this chapter, you will learn to write, test and debug Client-side JavaScript.
6.1 Hands-on Exercises
Javascript can enhance the dynamics and interactive features of your page by allowing you to
perform calculations, check forms, write interactive games, add special effects, customize graphics
selections, create security passwords and more. JavaScript is an Object Oriented Programming
(OOP) language. An OOP language allows you to define your own objects and make your own
variable types.
Methods
Most objects have a certain collection of things that they can do. Different objects can do
different things. A new document is opened with the method document.open() You
can write "Hello World" into a document by typing document.write("Hello
World") . open() and write() are both methods of the object: document.
Events
Events are how we trigger our functions to run. The easiest example is a button, whose
definition includes the words onClick="run_my_function()". The onClick
event, as its name implies, will run the function when the user clicks on the button. Other
events include OnMouseOver, OnMouseOut, OnFocus, OnBlur, OnLoad,
and OnUnload.
The following table is a list of objects and their methods and properties that are commonly
used in client-side programming.
Task Objects with methods and properties
window.open(“Mypage.html”, ”window
To open a new window and alter
name”,”height=200,width=400, status = no,
its appearance
toolbar=no, menubar=no, location = no”)
1. Open a text editor and type the following HTML document that contains JavaScript code. Save
the file as ‘Basic.html’.
2. Changing the innerHTML property of an HTML element is a common way to display data in
your webpage. Your code should produce the following output on the browser.
3. Another way to display data using JavaScript is by using the alert method. Try adding this
code into your HTML document.
<form name="myform">
<input type="button" value="Click here"
onClick="window.alert('Thank you!'); ">
1. The JavaScript you have created so far have only applied to the document itself. Internal scripts
apply only to the document in which they were created. Now, you’ll learn how to import an
external JavaScript which contains the script you defined in respective document. The reason
of creating external JavaScript is to enable user to run the same JavaScript on several pages,
without having to write the same script on every page.
2. Open a new page on a text editor and copy all the JavaScript you have created in the
‘Basic.html’ in Exercise 6.1.1. Save the external JavaScript file with an ‘external.js’ file
extension in the same folder with the html document. Please remember that the external script
cannot contain the <script> tag.
3. To embed the external JavaScript in Basic.html, point to the ‘external.js’ file in the ‘src’
attribute of the <script> tag like below. Remember to place the script exactly where you
normally would write the script.
<!DOCTYPE html>
<html>
<head>
<script src=”external.js”></script>
</head>
<body> </body>
</html>
4. Open the Basic.html on the browser. Your code should produce the output as same Exercise
6.1.1.
Knowing how to dynamically change the styles applied to a HTML document is extremely
useful for building modern, rich interactive web pages. Style modifications can improve the
efficiency of web experiences while showing and hiding content can help to avoid needless
trips to the server in certain circumstances.
2. With JavaScript, you are able to change HTML attributes, elements and CSS directly by
manipulating the objects in your HTML document.
6.1.4 Variables, Functions, Conditions and Loop
JavaScript supports much of the structured programming syntax from C. Window is treated as an
object which has properties and method to access. The alert, confirm and prompt
message boxes are methods of the interface window object.
Window (PROPERTIES): document, bgcolor, fgcolor, default
status, frame, parent, referrer, lastmodified, history,
location, name etc.
Window (METHODS): alert, prompt, confirm, write, writeln,
close, open, setTimeout, reload, clearTimeout, blur, focus etc.
3. To demonstrate this, type down this code below and save your file as dialogbox.html. The
Confirm box is most often used to confirm an important action that are taking place on a
website. For example, they may be used to confirm an order submission or notify visitors that
a link they clicked will take them to another website.
<!DOCTYPE html>
<html>
<head>
<title>Dialog Boxes and Event Handlers</title>
<script>
function myConfirm(){
var answer = confirm("You are about to leave our site. We are not
responsible for a any third party websites contents. Are you sure you
want to proceed?");
if(answer)
{ window.location="http://www.softpedia.com"; }
else
{ document.getElementById("link").innerHTML = "Thanks for
sticking around.";
}
}
</script>
</head>
<body>
<p id="link" onclick="myConfirm()">Download Apps at Softpedia</p>
</body>
</html>
4. An interactive dialogue box will be displayed with the message-jump to another URL. If you
click ‘OK’ you will be taken to that page because the window.location property is
addressed to that place. If you click ‘Cancel’ then it will be cancelled.
5. When a user triggers an event, your browser usually does something in response. Click a link,
and it loads up the page in the link's href. Click into a form field and it receives the browser's
focus. These are the default event handlers for each object in a HTML page. When we write
our own event handlers, we write them directly into the HTML code so the browser knows
which element we're addressing, and add in new commands on top of the existing default
actions.
6. Event Handlers aren't scripts in themselves, but often use variables, methods and functions
from scripts to perform their action. To demonstrate this, insert this code into the <body> tag.
<p id="link" onclick="myPrompt()">Calculate the sum of 2 numbers</p>
8. The Prompt box is useful when you want to pop-up a text box to get user input. Thus it
enables you to interact with the user. The user needs to fill in the field and then click OK. The
parseInt() function converts a string to an integer value.
9. Close your previous file and create a new HTML document. Insert this code and save it as
SwitchCase.html
<html>
<head><title>More Examples</title></head>
<body>
<p id="winner"></p>
<script type="text/javascript">
var number = prompt("Congratulations for being the winner of our
lucky draw contest. Enter a number between 1 to 3 to collect your
prize.", 0)
switch (number)
{
case (number = "1"):
{ document.getElementById("winner").innerHTML = "You have won
yourself an IPhone!" ;
var pic = document.createElement("img");
pic.setAttribute('src',
'http://d3nevzfk7ii3be.cloudfront.net/igi/RaW5CBghXHFNYe1s.large');
document.body.appendChild(pic);
}
break;
case (number = "2"):
{
document.getElementById("winner").innerHTML = "You have won
yourself an IPod!!" ;
var pic = document.createElement("img");
pic.setAttribute('src', 'http://www.ilectronics.co.uk/wp-
content/uploads/1970/01/ipod-classic-2ndgen-e1422649824866.jpg');
document.body.appendChild(pic);
}
break;
case (number = "3"):
{
document.getElementById("winner").innerHTML = "You have won
yourself an iPad!!" ;
var pic = document.createElement("img");
pic.setAttribute('src', 'http://evostore.com.np/wp-
content/uploads/2017/08/MM2A2_AV2.jpg');
document.body.appendChild(pic);
}
break;
default:
alert("Sorry, wrong value.");
break;
}
</script>
</body>
</html>
10. So far, you have explored Javascript programming syntax such as variables, functions,
operators, expressions, assignment, relational, logical arithmetic, operators, control structures
such as if.. else and switch..case statements. Next, you will work with more
arithmetic operations and iteration loops in your program.
1. The For loop is used when you know in advance how many times the script should perform.
Type down the code below and save your file as LoopFor.html.
<html>
<head>
<title>Temperature Converter Table</title>
</head>
<body>
<table border=3>
<tr><td>CELSIUS</td><td>FAHRENHEIT</td></tr>
<script language="javascript">
for (celsius=-8; celsius<=47; celsius=celsius+1)
{
document.write("<tr><td>"+celsius+"</td><td>"
+((celsius*9/5)+32)+"</td></tr>");
}
</script>
</table>
</body>
</html>
2. The While loop is used when you want the loop to continue until a certain condition becomes
true. Create a new HTML document named LoopWhile.html and write this code.
<!DOCTYPE html>
<html>
<head><title>Quick Quiz</title></head>
<body>
<script>
var x=5*5;
x=prompt("What is 5 x 5?");
while (x != 25)
{
alert("Wrong answer");
x=prompt("What is 5 x 5?",0);
}
</script> <p id="correct"></p> <script>
document.getElementById("correct").innerHTML = "Correct! The answer
is " + x + ".";
</script>
</body>
</html>
3. You have declared variable x and initialized 25. Then, you set it equal to the prompt box. The
prompt box asks the product of 5x5 and continues asking until true answer is provided. It also
informs each wrong attempts or each loop
4. Try modifying the current code using a Do.. While loop instead.
Among the wide array of features offered by the Math object are several special values such as PI,
natural logarithms, and common square roots, trigonometric methods, rounding methods, an
absolute value method, and more. These can be used to make complex calculations in Javascript
when needed.
Name Usage
Abs() Calculates the absolute value of a number.
Acos() Calculates the arc cosine of a number—returns result in radians.
Asin() Calculates the arc sine of a number—returns result in radians.
Atan() Calculates the arc tangent of a number—returns result in radians.
Ceil() Returns the next integer greater than or equal to a number.
Cos() Calculates the cosine of a number.
Exp() Calculates e to the power of a number.
floor() Returns the next integer less than or equal to a number.
log() Calculates the natural logarithm of a number.
max() Returns the greater of two numbers—takes two arguments.
min() Returns the least of two numbers—takes two arguments
Calculates the value of one number to the power of a second number—
pow()
takes two arguments.
Returns a random number between zero and one. Presently, this is only
random()
implemented in UNIX versions of Navigator 2.0.
round() Rounds a number to the nearest integer.
sin() Calculates the sine of a number.
sqrt() Calculates the square root of a number.
tan() Calculates the tangent of a number.
1. In this exercise, you are going to use the pow() method to calculate the volume of a cube based
on the side’s value.
2. Type down this code below and save your file as Math.html.
<!DOCTYPE html>
<html>
<head><title>Volume of Cube</title></head>
<body>
<script>
var s, vol;
s = parseInt(window.prompt("Enter the side of the volume","0"));
vol = Math.pow(s,3);
</script>