Client-Side Programming With JavaScript
Client-Side Programming With JavaScript
Level I - Semester 2
Variable Declaration Variable data types not Variable data types must be
declared. declared.
10
© 2020 e-Learning Centre, UCSC
JavaScript coding and Execution
12
© 2020 e-Learning Centre, UCSC
To learn JavaScript you will need to learn some of its language syntax.
However, a good strategy is to learn the basics, and then use and adapt other
people's JavaScript. There are plenty of sites on the internet offering free
JavaScript (see slide 4) with the calculator example. Other useful addresses are
provided in the notes of last slide.
As with HTML, JavaScript can be written in a text editor and viewed in a browser. As
it is a programming language the syntax is quite strict (compared to HTML). It is
also a good idea to make sure your HTML is up to scratch as this will save you time.
The hands-on exercises contain an refresher exercise on HTML forms.
Tips
• Check your statements are on one line
• Check your " and ' quotes match
• Take care with capitalisation
• Lay it out neatly - use tabs
Some tips for debugging and clarity to make it easier for you (the trainer) as well as
for the audience. Follow the conventions we have used for capitalisation which will
make it easier to read / find mistakes.
References:An alternative site with ready made scripts for download:
http://builder.com.com/
Follow links to Web Development and then JavaScript to see a number of good
examples.
How to Embed JavaScript
• <html> <body>
<script type="text/javascript"> ... </script>
</body> </html>
<html>
<body>
<script type="text/javascript"> document.write("Hello World!") </script>
</body>
</html>
<SCRIPT LANGUAGE=“JavaScript”>
JavaScript statements here
</SCRIPT>
14
© 2020 e-Learning Centre, UCSC
Embedding JavaScript in XHTML
• <script> tag is used to embed JavaScript code in
XHTML code of a web page
• The <script> tag can be used anywhere inside the code
but it is usually embedded right before of after the
<head> tag closes
• Any number of <script> tags can be embedded, but
usually one tag is enough
• Nesting <script> tags is prohibited and generates errors
• HTML editors do not follow the <script> tag guidelines
and embed the tag any where and any number of times
16
© 2020 e-Learning Centre, UCSC
JavaScript Statements
<html>
<head><title>My Page</title></head>
<body>
<script language="JavaScript">
document.write('This is my first →
JavaScript Page');
Note the symbol for
</script> line continuation
</body>
</html>
17
© 2020 e-Learning Centre, UCSC
JavaScript can be contained either in the header section of an HTML page or in the
body. This JavaScript statement is shown as a pure JavaScript statement within
SCRIPT tags.
Notice that there is no HTML in the body of this page at all. (Demonstrate what this
JavaScript looks like in a web browser).
This statement writes a line of text on a web page.
The command document.write is a standard function in JavaScript to write text to
the page. The following is a more technical explanation for background information
only:
document.write is derived from the JavaScript object model (not covered in detail
here). It works on the principle that all document and browser elements have an
object name (document, window, image etc) and can each has various properties
that can be manipulated. The object hierarchy means that individual elements can
be uniquely identified i.e. document.myform.mytext would refer to the text entry
named mytext within the form called myform within the current page (document).
The arrow symbol '→' is used in these slides and in the workbook to indicate
where a JavaScript statement should be typed on one line without a break. A
line break in the wrong place will stop JavaScript from working.e.g.
document.write('This is my first →
JavaScript Page');
document.write('<h1>This is my first →
JavaScript Page</h1>');
HTML written
</script> inside JavaScript
</body>
</html>
This example demonstrates that anything included within the quotes in the
document.write statement is printed to the screen, and this includes HTML tags. The
<h1> tag is delivered to the browser along with the text, and the browser would
interpret it as a normal HTML file, displaying the text in the Heading 1 style.
IMPORTANT NOTE:
This example shows a JavaScript statement in the <body> of the web page.
It is possible to include JavaScript statements in the <head> section of a web page
but care must be taken that they do not try to access items that don't exist until the
page has loaded (e.g. form elements, links, images). The web browser parses
(reads through and executes) any script commands as it displays the page.
In most cases it is common sense that dictates where a statement should be
placed.
If, in the above example, document.write was placed in the <head> of the page, the
text "This is my first JavaScript Page" would appear in the <head> of the finished
page – this would be incorrect – although modern browsers will let you get away
with it!
In some circumstances you may wish to use document.write in the <head> - for
example to dynamically generate <meta> or <title> tags. Such uses are not
considered here.
JavaScript functions are typically defined in the <head> section of a web page as
they do not normally execute until they have been triggered elsewhere. The use of
functions in JavaScript is covered in the Netskills Training Module: "Further
JavaScript (Enhancing JavaScript with Functions and Events)"
JavaScript Statements
<html>
<head><title>My Page</title></head>
<body>
<p>
<a href="myfile.html">My Page</a>
<br />
<a href="myfile.html"
onMouseover="window.alert('Hello');">
My Page</A>
</p>
JavaScript written
</body>
An Event inside HTML
</html>
Compare this example with the previous one. This time the JavaScript is written
inside the HTML tags and there are no <script> tags.
In this case if the browser is JavaScript-enabled it will process the commands when
it needs to. If the browser doesn't understand JavaScript it will ignore the extra code
(it should see it as an HTML attribute that it cannot process and therefore ignores,
although very old browsers my throw an error)
This example demonstrates an HTML hyperlink, but notice the JavaScript enclosed
within the <a href.. tag of the second link.
onMouseOver is referring to an event. That is, this JavaScript will happen in
response to something that the user does e.g click a button, or in this case, when
they move the mouse over the link (this will not happen if you move your mouse
over the first link!).
window.alert will display what is called an alert box on the screen containing the
text specified, in this case, "hello".
The first link will behave normally.
How to Notate Comments
• Use a double slash (//)
• Web browsers interprets a single line proceeded by // As a
comment
Num=20;
Document.write(“The price is”,Num, “.Thank you.”);
© 2020 e-Learning Centre, UCSC 21
Variables …
• A variable is a symbolic name that stores a value and has the some
characteristics
• Identifiers
The name of the variable is its identifier
It must begin with a letter, underscore, or $ sign
It cannot begin with a number or other characters
JavaScript is case-sensitive
Examples: test, Test, jam234, _best, $abc,
a_1$4
• Types
Data types are implicit and are converted automatically
The first use of a variable declares its types
Types can be numbers (integer or real), logical (boolean), or string
Examples: 3, 40, -10.5, true, false, “zeid”,
“9abc”
You can also declare multiple variables with the same var keyword as follows −
For instance, you might create a variable named money and assign the value 2000.50
to it later. For another variable, you can assign a value at the time of initialization as
follows.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of
any data type. Unlike many other languages, you don't have to tell JavaScript during
variable declaration what type of value the variable will hold. The value type of a variable
can change during the execution of a program and JavaScript takes care of it
automatically.
24
© 2020 e-Learning Centre, UCSC
Variables…
JavaScript variables have only two scopes.
•Global Variables − A global variable has global scope which means it can be
defined anywhere in your JavaScript code.
•Local Variables − A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>
25 25
© 2020 e-Learning Centre, UCSC
Variables
• A variable can hold data such as numbers or characters
• A variable name must with a letter,
• an underscore(“_”)
• or a dollar($)
<body>
<script language="javascript">
<!--
a=100;
document.write(a);
abc=20-10;
document.write(abc);
_abc=30-5;
document.write(_abc);
$abc=40-2;
document.write($abc);
answer=100-10*2;
document.write(answer);
//-->
</script>
</body> 26
© 2020 e-Learning Centre, UCSC
• Scope
Variables
The code block within which the variable is available
Global variable is available everywhere
Local variable is available only inside a code block
Global variables are easy to manage but a bad habit
• Constants
Read only variables defined by a const keyword
Cannot change values or be re declared
Examples: const x=22
• Literals
Fixed values (hard-coded values) in JavaScript
Nesting literals needs extra care
Examples: 3.5, false, “Hello”
• Data Type Conversion
JavaScript converts data types automatically, but creates confusion
Examples: answer=true, answer=20
• Escaping and Special Characters
Backslash is the escaping character and is used to define special
ones © 2020 e-Learning Centre, UCSC
27
Statements
• A statement uses an assignment operator, an equal sign
• The operator has two operands on each of its side and
the value of the right operand is assigned to the left one
• Example : x = y
• Values of right operand must always be known, if not,
and error is generated
• Statement must be only one line long and cannot be
broken
• Semicolon (;) is used to separate statements
• JavaScript also provides comment statements
TRUE
Process
Increment
© 2020 e-Learning Centre, UCSC
33 33
Conditional Branching
• Use the if statement to perform separate statements according to a condition
if
FALSE
if (condition){ Condition
statement for when condition1 is true;
} else { TRUE
statement for when condition1 false Process1 Process2
}
Else if
FALSE
if (condition1){ Condition1
statement for when condition1 is true;
} else if (condition2){ TRUE
FALSE
statement for when condition2 true;
} else { Process1 Condition2
statements for when all condition are false; TRUE
}
Process2 Process3
34
© 2020 e-Learning Centre, UCSC
Functions
• A function groups together a set of statements under a named subroutine.
A function can be called by that name whenever its action is required.
• Reasons for use;
• Reuse script
– You can simply call the function as necessary and avoid rewriting
the entire block of code again.
• Clarify your program
– Functions make the purpose of each section clear and thus
makes your script coding more efficient.
• Easy maintenance
– You can simply change that part
• What is an argument
• Arguments are variables used in the functions. The values in the
variable are passed on by the function call
• What is a return value?
• A return value is value returned to the calling expression. It can be
omitted if a return value is not necessary.
35
© 2020 e-Learning Centre, UCSC
Defining Functions
• How to define and call functions;
<HTML>
<HEAD>
<SCRIPT LANGUAGE=“JavaScript”>
Function function_name (argument, argument,…) {
my_statemetn;
: 1
3
return return_value;
The Function
}
returned Definition
</SCRIPT>
value
</HEAD>
from the
<BODY>
function is
<SCRIPT LANGUAGE=“JavaScript”>
assigned
variable_name = function_name (argument, argument,…); 2
to this
</SCRIPT>
variable Calling a
</BODY>
</HTML> function
<html><head>
<title>kansu.html </title>
<script language="javascript">
function kansu (i){
result= i*1.05;
return result;
}
</script>
</head>
<body>
The result of the multipication of 100 and 1.05 is:
<script language="javascript">
<!--
x=kansu(100);
document.write(x);
//-->
</script>
</body></html> © 2020 e-Learning Centre, UCSC
37
Event Procedures / handlers
• What are events
• Events are actions that occur usually as a result of something a user does such as clicking
a mouse.
• Event Handlers
• Events handlers identify such events and they can be placed within the HTML tags.
41
© 2020 e-Learning Centre, UCSC
Example Script for Closing a Window
<HTML>
<HEAD>
<TITLE>new.html</TITLE>
</HEAD>
<BODY bgcolor="ffcc99" onload="setTimeout('window.close()',10000)">
I am a cat!!<BR><BR>
<IMG SRC = 'image/neko.gif'><BR><BR>
<script language="javascript">
<!--
document.write("The last modified date/time:", document.lastModified,"<br>");
//--> </script>
<form>
<input type="button" value="close" onClick="window.close()">
</form>
</BODY>
</HTML>
42
© 2020 e-Learning Centre, UCSC
Example Script for Last Modified Date and Time
<html>
<head>
<title>The last modified date and time</title>
</head>
<body>
<script language="javascript">
<!--
document.write("The last modified date/time:", document.lastModified);
//-->
</script>
</body>
</html>
43
© 2020 e-Learning Centre, UCSC
Input and Output
• Client-side JavaScript has limited input/output utilities
due to security reasons
• The input functions available are:
prompt (message, default) → takes an input and
returns it to the JavaScript program
confirm (question) → asks the user to confirm an
input value and return a boolean value
• The output functions available are:
document.write (string)
alert (string)
Both these functions are used to output results in a web
page
44
© 2020 e-Learning Centre, UCSC
HTML Forms and JavaScript
• JavaScript is very good at processing user
input in the web browser
• HTML <form> elements receive input
• Forms and form elements have unique names
– Each unique element can be identified
– Uses JavaScript Document Object Model (DOM)
JavaScript is very useful for processing and manipulating user input and form
elements.
A common way of obtaining input is via the HTML <form> elements which can
provide text entry boxes, selection boxes, menus and buttons. Form elements can
be named and hence uniquely identified within the JavaScript object model.
Naming Form Elements in HTML
<form name="addressform">
Name: <input name="yourname"><br />
Phone: <input name="phone"><br />
Email: <input name="email"><br />
</form>
This example shows a simple form. Notice the name attribute is used at all points -
to name the form, and to name each element within the form.
How JavaScript uses the name attribute is described next.
Forms and JavaScript
document.formname.elementname.value
Thus:
document.addressform.yourname.value
document.addressform.phone.value
document.addressform.email.value
47
© 2020 e-Learning Centre, UCSC
To refer to the value that a user has typed in a text box, you use the following
naming system:
document.formname.elementname.value
This is a naming convention derived from the JavaScript object model:
document refers to the page displayed in the browser.
formname is supplied by the page author as the name attribute of the <form>
tag - in the example it is addressform and refers to the whole form.
elementname is supplied by the page author using the name attribute of the
<input> tag.
value is a predefined term which refers to the text typed in by the user.
Using Form Data
Personalising an alert box
<form name="alertform">
Enter your name:
<input type="text" name="yourname">
<input type="button" value= "Go"
onClick="window.alert('Hello ' + →
document.alertform.yourname.value);">
</form>
48
© 2020 e-Learning Centre, UCSC
:
:
//-->
</script> </head><body>
Please fill up these text boxes(all inputs are required).<br>
<form action ="flm.cgi" name="fm" onSubmit="return checkForm()">
Postal Code:
<input type="text" Name="yubin" size="8"><br>
Address:
<input type="text" Name="address" size="40"><br>
Name:
<input type="text" Name="name" size="20"><br>
<input type="submit" value="Submit">
53
© 2020 e-Learning Centre, UCSC
Summary
• JavaScript is a powerful language and makes a web page
dynamic
• JavaScript and Java are fundamentally different in most
ways
• JavaScript code is embedded in XHTML code
• JavaScript code is written and tested like XHTML code
• JavaScript begins with variables
• JavaScript uses statements to build code block
• JavaScript has a rich set of operators
• JavaScript has control structures to control code
execution
• Code execution follows top to bottom, left to right rule
• Input and output is handled using basic functions 54
© 2020 e-Learning Centre, UCSC
Reference
• https://www.tutorialspoint.com/javascript/
• https://www.w3schools.com/js/
• https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-
oriented_JS
• http://dynamicdrive.com/
55
© 2020 e-Learning Centre, UCSC