ITEC244 JavaScript

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

ITEC244 - Internet Technology

JavaScript
What is JavaScript?

JavaScript is a client-side scripting language – this means that the code runs on the client’s computer
instead of the server. This means that JavaScript functionality can work only is the user’s machine has it
enabled. JavaScript is the most commonly used scripting language today and as with other scripting
languages it enables the creation of dynamic and/or interactive web pages which makes a website much
more useful and functional.

JavaScript can be used for several purposes on a webpage some of which are:

 Perform a particular action in response to an event


 Perform form validation
 Edit the content of a webpage by writing to html elements
 Create cookies and track visitors to a website.

It is important to understand that having all these features fully performed on the client machine is of
great advantage… it means that bandwidth use is optimized. If we could not do the above using our
client side scripting we would have to send every request to the server! This would result in a
tremendous increase in network traffic and a significant increase in latency i.e. more delays before
requests can be serviced.

For this course we will be primarily concerned with form validation and event handling. The primary
resource used for this course will be the wcschools tutorials found at:
http://www.w3schools.com/js/js_intro.asp

What is the HTML DOM

In HTML whenever a web page is loaded by the browser a ‘model’ of the page layout is created. This
model is called the Document Object Model or DOM and is a W3C standard. The importance of this
DOM is that it allows easy location and manipulation of individual elements on the page. The model
created is essentially a ‘tree’ structure – see the following illustration - which makes it much more
efficient to search through a web page for a particular element. Once an element can be accessed via
this structure we can:

1. Change its content – e.g. change the text in a paragraph


2. Change the element’s style – e.g. set a new CSS style for the element
3. Add a new element to the existing one – e.g. add a new div element to a page or a new row to
an existing table.
4. Delete an existing HTML element from the web page altogether.

Lecturer: Alicia Dennis-Nagee


1
ITEC244 - Internet Technology
JavaScript
The DOM provides us with the structure, methods and events to facilitate all the operations
mentioned above.

Original image at http://www.w3schools.com/js/js_htmldom.asp

NB: there are three parts of the DOM standard (Core DOM, XML DOM and HTML DOM) we will only be
using the HTML DOM for this course.

The three features of the DOM we will use in this section with our JavaScript are the Document object,
getElementById method and the innerHTML property.

Document refers to the actual web page itself. In order to access any element on the web page we
must first refer to the containing document object

getElementById – this method searches through the document tree in search of an element whose
id attribute is set to the provided value – we will see examples in code below

innerHTML – this allows us access to the actual value of an HTML element. It gives us the ability to
retrieve or set the content of our page elements – again we will see examples below.

There are many more methods and properties of the DOM. We will meet and use some of them as we
progress through the course.

How do we use JavaScript?

JavaScript (JS) can be included in one of three ways into our webpage. Like CSS code we can use JS
inline, define it in our head section of our page or use an external JS page which can be linked to from
multiple pages of our website.

Lecturer: Alicia Dennis-Nagee


2
ITEC244 - Internet Technology
JavaScript
Inline JS – when we write JS within the body section of our code using the <script> tag the JS code is
executed as soon as the webpage is loaded. This may be useful at times however since inline code
cannot be used after the page is loaded hence it is not a good option for making pages interactive and
not at all an option for form validation or event handling. Here is a simple example of inline JS code
which writes a message to the webpage when it is loaded:

<body>
<script type=”text/javascript”>
Document.write(“Hello World”);
</script>
</body>

This piece of code will simply display the words Hello World on the web page when it loads.

Here is another example where JS is used to write html to a paragraph element on a page. Note that the
JS is placed after the paragraph element because the JS is executed as soon as it is encountered when it
is used inline. As such we must not encounter the JS before the paragraph element to which it refers has
already been created.

<html>
<head>
<title>Learning JavaScript</title>
</head>
<body>
<p id="learningJS">
</p>
<script type="text/javascript">
document.getElementById('learningJS').innerHTML="<br/><strong
>This is an example of using the getElementById and innerHTML
functions in JavaScript</strong><br/> <br/>Thank you!";
</script>
</body>
</html>

Lecturer: Alicia Dennis-Nagee


3
ITEC244 - Internet Technology
JavaScript
This piece of code will insert the html text within the double quotes after the innerHTML function into
the empty paragraph element above it. In essence the JavaScript changes the html of the page to the
following as soon as the page loads… too fast for us to actually see the change occurring!

<html>
<head>
<title>Learning JavaScript</title>
</head>
<body>
<p id="learningJS">
<br/><strong> This is an example of using the getElementById
and innerHTML functions in JavaScript</strong><br/> <br/>Thank
you!
</p>
</body>
</html>

Lecturer: Alicia Dennis-Nagee


4
ITEC244 - Internet Technology
JavaScript
JavaScript in the page header

Often we want to use JavaScript to perform a task when an ‘event’ occurs. An event is an action which
can be performed on/with a page element such as a mouse click, mouse double click, rollover etc. You
can view all the events relevant to a particular page element on the w3schols website. When we want
JS to be used in response to an event we need to use JS functions. JS functions are predefined blocks of
code which are ‘called’ when a particular event occurs. Let us look at an example of some JS being called
when a button is clicked on a form – our function addition() is called based on the ‘onclick’
event of the input button element ‘sum’.

<html>
<head>
<title>My first Form </title>
<script type="text/javascript">
function addition(){
var num1 = document.getElementById('fnum').value;
var num2 = document.getElementById('snum').value;
var sum = parseInt(num1) + Number(num2);
alert(sum);
}
</script>
</head>
<body>
<form method="post" action="math.html">
First Number &nbsp &nbsp &nbsp
<input type="text" name="fnum" id ="fnum" >
<br/><br/>
Second Number &nbsp &nbsp &nbsp
<input type="text" name="snum" id="snum">

<br/><br/>

<input type ="button" id="sum" value ="Sum"


onclick="addition();">
</form>
</body>
</html>

There are several things to note in the above code:

Lecturer: Alicia Dennis-Nagee


5
ITEC244 - Internet Technology
JavaScript

getElementById() function – this function belongs to the HTML document object. It searches the
current document for an element (any valid html element) with the specified id. Remember that we
specified an id for our element within in its tag using the id attribute

e.g. <input type="text" name="fnum" id ="fnum" >

Here the input TextField we created was given the id ‘fnum’ so when we use the line
document.getElementById(‘fnum’) in our JS the actual textfield object/element is returned to us.
In our code though this was not all… we said document.getElementById(‘fnum’).value – what
the .value does is retrieve from the fnum element the value it currently contains.

parseInt() function – this is a JavaScript function. This function accepts a String parameter/input and
converts it to an integer. It retrieves only one value so if the ‘fnum’ textfield contained more than one
number value separated by spaces parseInt() would only convert the first text number to an actual
numeric piece of data.

Number() function – this is another JS function which accepts an object and converts its value to a
number. If the objects number cannot be converted to a numeric value NaN is returned. Nan is a special
response which means ‘Not a Number’ and serves a purpose very much like a null which you have seen
before in java programming.

NB. By default all data retrieved from a textfield or textarea is retrieved as a String. This is why in order
for us to perform the calculation in out JS code it was necessary for us to first convert the values
retrieved to some form of numeric data.

The alert() method – this is a JS method which is used to create pop-up boxes containing a text
message to the user. The pop-up is modal in that it prevents the user from proceeding with work in the
browser until the box is closed. Any String placed in the parentheses will be displayed to the user. The
String can be a combination of literal values and/or variables just as we would to concatenate these in
java.

Lecturer: Alicia Dennis-Nagee


6
ITEC244 - Internet Technology
JavaScript
Variables in JavaScript

Creation of variables – variable creation in JS is VERY simple. There is no data type declaration so you
simply use the keyword var followed by the name you wish to give your variable. The variable is treated
as an object and so no data type is necessary: e.g. var my_var = 5679;

NB. All the rules/conventions learned in java are applicable to JS for the naming of variables. Also, all the
assignment, comparison, logical and mathematical operators learnt in java are applicable to JS.

External JavaScript

It is possible to declare all our JS functions and variables in a separate document and link to it from
within the header of our individual web-pages using the same script tag but with a src attribute
specified. This is very similar to using an external CSS file in the way we are able to use the JS members
from any webpage which links to the document. Here is an example using an external JS file.

<head>
<title>My first Form </title>
<script type="text/javascript" src=”myJS.js”>

</script>
</head>
<body>
<form method="post" action="math.html">
First Number &nbsp &nbsp &nbsp
<input type="text" name="fnum" id ="fnum" >
<br/><br/>
Second Number &nbsp &nbsp &nbsp
<input type="text" name="snum" id="snum">

<br/><br/>

<input type ="button" id="diff" value ="Difference"


onclick="subtraction();">
</form>
</body>
</html>

Lecturer: Alicia Dennis-Nagee


7
ITEC244 - Internet Technology
JavaScript

function subtraction(){
var num1 = document.getElementById('fnum').value;
var num2 = document.getElementById('snum').value;
var diff = parseFloat(num1) - Number(num2);
alert(diff);
}

The above function (along with others) will be saved in a separate file called myJS.js and saved in the
same path as the HTML and CSS documents

Form Validation

One of the most useful purposes for the inclusion of JS on a website is the ability to use it to validate
data entered on a form before the user submits the info to the server for processing. Let us look at some
of the most common validation done on forms.

Ensuring that fields are filled

Sometimes we want to ensure that the user does not submit an empty form to the server for
processing. This can be prevented by using some simple JavaScript

function validate(){

var x=document.forms["myForm"]["fname"].value;

if (x==null || x==""){

alert("First name must be filled out");

return false;

Notice above that instead of the getElementById(“element_id”).value we have used


document.forms["myForm"]["fname"].value this is an alternative way to access our website
elements from our JS see http://www.w3schools.com/js/js_htmldom_document.asp for more ways to
access page elements

Lecturer: Alicia Dennis-Nagee


8

You might also like