[Go to site: main page, start]

0% found this document useful (0 votes)
9 views8 pages

JavaScript for Dynamic Web Pages

The document discusses JavaScript, describing it as a client-side scripting language that allows dynamic web pages. It can be used for event handling, form validation, and editing web page content. Using JavaScript avoids sending requests to servers, optimizing bandwidth. The document also discusses how the HTML DOM creates a model of the web page that JavaScript can access and manipulate elements. It provides examples of including JavaScript inline, in the page head, and with external files.

Uploaded by

priyanka
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)
9 views8 pages

JavaScript for Dynamic Web Pages

The document discusses JavaScript, describing it as a client-side scripting language that allows dynamic web pages. It can be used for event handling, form validation, and editing web page content. Using JavaScript avoids sending requests to servers, optimizing bandwidth. The document also discusses how the HTML DOM creates a model of the web page that JavaScript can access and manipulate elements. It provides examples of including JavaScript inline, in the page head, and with external files.

Uploaded by

priyanka
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

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:
[Link]

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 [Link]

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”>
[Link](“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">
[Link]('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 = [Link]('fnum').value;
var num2 = [Link]('snum').value;
var sum = parseInt(num1) + Number(num2);
alert(sum);
}
</script>
</head>
<body>
<form method="post" action="[Link]">
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"


> </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
[Link](‘fnum’) in our JS the actual textfield object/element is returned to us.
In our code though this was not all… we said [Link](‘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=”[Link]”>

</script>
</head>
<body>
<form method="post" action="[Link]">
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"


> </form>
</body>
</html>

Lecturer: Alicia Dennis-Nagee


7
ITEC244 - Internet Technology
JavaScript

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

The above function (along with others) will be saved in a separate file called [Link] 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=[Link]["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


[Link]["myForm"]["fname"].value this is an alternative way to access our website
elements from our JS see [Link] for more ways to
access page elements

Lecturer: Alicia Dennis-Nagee


8

Common questions

Powered by AI

JavaScript handles numeric conversion using functions like parseInt and Number. parseInt converts a string to an integer, retrieving only the first number it encounters, which can be problematic if not all parts of the string are numeric . Number converts a value to a number and returns NaN if conversion fails. Care must be taken to ensure strings have valid numeric content to avoid unexpected NaN results .

The DOM provides a tree structure model of the webpage, enabling access to and manipulation of individual HTML elements. JavaScript interacts with this model using methods such as getElementById and properties like innerHTML to dynamically change content, styles, or even delete elements . This manipulation is key to making web pages interactive and responsive without reloading.

The getElementById method is crucial for accessing specific elements in the DOM using their 'id'. It returns the first element with the specified id, allowing developers to modify its content, style, or other attributes . This method is efficient for targeted operations within a potentially large and complex document structure.

Converting form inputs to numeric data types is essential because data retrieved from input fields is typically string-based. Arithmetic operations directly on strings can lead to unexpected results, such as concatenation instead of addition. Functions like parseInt and Number ensure the data is in a numeric format suitable for calculations . Without conversion, the logic would fail, resulting in incorrect outputs or errors.

JavaScript can validate mandatory form fields by checking the value of input elements before submission. Using techniques like document.forms['formName']['inputName'].value, developers can verify that values are not null or empty. If a field is left blank, JavaScript can prompt users with alerts to ensure necessary information is provided before allowing form submission to the server . This pre-validation enhances data integrity and user experience.

JavaScript functions can be executed in response to HTML events, such as clicks or key presses, using event handlers like onclick. This integration allows developers to specify JavaScript functions that run when these events occur, enabling dynamic and interactive web behavior. For example, clicking a button can trigger calculations or form validation without refreshing the page .

External JavaScript files allow developers to separate code from HTML, making it easier to manage and reuse across multiple web pages. This separation improves the maintainability of the codebase, as changes made in the JavaScript file will automatically apply wherever the file is linked . It promotes cleaner code and better organization, aligning with best practices in web development.

The alert method in JavaScript shows a pop-up dialog with a specified message, effectively capturing the user's attention as it is modal, preventing other interactions until closed . However, frequent use of alerts can disrupt user experience, as users cannot proceed with other tasks until the alert is dismissed. It lacks customization options beyond simple string display, limiting its use in complex applications.

JavaScript form validation, being client-side, allows for immediate feedback to users without the need for data to be sent to the server, thus optimizing bandwidth and reducing network traffic and latency . This real-time validation means errors can be caught and corrected before the form is submitted, enhancing the user experience and reducing server load.

Inline JavaScript is not ideal for making pages interactive or for functionalities like form validation or event handling, as the code is executed immediately and cannot be used once the page has loaded . This limits the ability to respond to user interactions dynamically. It's often better to use external JavaScript files for reusability and maintainability.

You might also like