Introduction to JavaScript - PowerPoint PPT Presentation

Introduction to javascript l.jpg
1 / 62

Introduction to JavaScript Fan Lu Contents Background HTML Fundamentals Introduction to JavaScript More Examples & Practices A Brief Summary Background (1/6)

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

Download Presentation

Introduction to JavaScript

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript

Introduction to javascript l.jpg

Introduction to JavaScript

Fan Lu

Contents l.jpg



HTML Fundamentals

Introduction to JavaScript

More Examples & Practices

A Brief Summary

Background 1 6 l.jpg

Background (1/6)

  • What is Computer Science?Computer science (CS) is the study of the theoretical foundations of information and computation and their implementation and application in computer systems.- there are so many sub-fields in CS,- but it does not involve the study of computer themselves.

Background 2 6 l.jpg

Background (2/6)

  • Fields of CS (an incomplete list):- Mathematical foundations - Algorithms and Data Structures - Programming Languages and Compilers - Concurrent, Parallel and Distributed systems - Software Engineering - Computer Architecture and Operating Systems - Communications - Databases - Artificial Intelligence - Computer Graphics - Human-Computer Interaction

Background 3 6 l.jpg

Background (3/6)

  • Communications – NetworkingA computer network is any set of computers or devices connected to each other. E.g. the Internet, or a small local area network (LAN) with two computers connected with standard networking cables.

  • The Internet: a "network of networks" that consists of millions of smaller domestic , academic, business and government networks, which together carry various information and services, such as Email, online chat, file transfer, and the interlinked web pages and other documents of the World Wide Web (WWW).

  • WWW:a system of interlinked, hypertext documents that runs over the Internet. With a Web browser, a user views Web pages that may contain text, images, and other multimedia and navigates between them using hyperlinks.- created around 1990, by Tim Berners-Lee and Robert Cailliau - Web standards: URI, HTTP, HTML

Background 4 6 l.jpg

Background (4/6)

  • URI – Uniform Resource Identifier- a compact string of characters used to identify or name a resource- can be classified as a locator or a name or both- URN ISBN:0-123-45678-9; URL

  • HTTP – Hyper Text Transfer Protocol- a method used to transfer information on the WWW- original purpose was to provide a way to publish/retrieve HTML pages- a request/response protocol between clients (web browsers) and servers via several intermediaries (proxies, gateways, and tunnels)

  • HTML – HyperText Markup Language- amarkup language for the creation of web pages- combines text and extra information about the text- JavaScript is embedded into HTML document

Background 5 6 l.jpg

Background (5/6)

  • Programming LanguagesA programming language is an artificial language that can be used to control the behavior of a machine, particularly a computer.- Thousands of different programming languages have been created- E.g. Java, C/C++, C#, Delphi, MATLAB, Pascal, Haskell, Fortran etc.

  • Scripting LanguagesUsually, computer programs are converted permanently into binary executable files before they are run. However, scripts remain in their original form and are interpreted command-by-command each time they are run.- Why scripting? Simplicity, flexibility, lightweight…- E.g. JavaScript, VBScript, Perl, Python, Ruby, PHP, Smalltalk, bash etc.

Background 6 6 l.jpg

Background (6/6)

  • JavaScript- is a popular scripting language that was initially developed for use within Web pages.-was developed by Netscape, which is an American computer services company, best known for its web browser.- works in conjunction with the Document Object Model (DOM), which is a platform- and language-independent standard object model for representing HTML or XML and related formats.-manipulates an HTML page after the page is delivered to the client, so-called Dynamic HTML (DHTML).- can be applied to both the client side and the server side, whereas this course is mainly about the client side scripting.

Contents9 l.jpg



HTML Fundamentals

Introduction to JavaScript

MoreExamples & Practices

A Brief Summary

Html 1 10 l.jpg

HTML (1/10)

  • A brief review of HTMLAn HTML file is a simple text file containing small markup tags, with a file type extension as .htm or .html. We can create an HTML files using any common text editor, such as Windows Notepad.Exercise 1: The first HTML page

  • Create a simple text file using notepad.

  • Type in the contents as shown on the left.

  • Save and close the file, and then rename it to “MyPage.html”.

  • Double-click on the file to open it using Internet Explorer.



<title>Title of page</title>



The first HTML page.

<b>This text is bold</b>



Html 2 10 l.jpg

HTML (2/10)

  • Structure of the first HTML page1) <html> … </html>These two tags tell the browser where is the start and the end of an HTML document.2) <head> … </head> The text between these tags is the header info, which is not displayed.3) <title> … </title> The text between these tags is a title to be displayed in the browser’s caption.4) <body> … </body> The text between these tags will be displayed in the browser window. 5) <b> … </b>The text between these tags will be displayed in a bold font.1, 2, 3, and 4 constitutes the minimum structure of an HTML document!

Html 3 10 l.jpg

HTML (3/10)

  • HTML ElementsThe “tags” we mentioned in the previous slide are formally called HTML Elements. There are several important issues we need to know about them:

  • HTML Elements are surrounded by angle brackets <>.

  • Tags normally come in pairs like <b> and </b>.

  • The text between the start and end tags is the element content.

  • HTML tags are not case sensitive, but according to the latest web standards, we should always use lowercase tags.

  • Tags can have attributes, which provide additional information to an HTML element. Attributes are always specified in the start tag of an HTML element, in the format: name=“value”, where values should always be enclosed in quotes (either double or single quotes).E.g. <table border="0"> … </table>

Html 4 10 l.jpg

HTML (4/10)

  • Basic HTML tags:1) Headings E.g. <h1>This is a heading</h1>, <h1> to <h6> are allowed2) Paragraphs E.g. <p>This is a paragraph</p>3) Line Breaks E.g. <p>This <br> is a para<br>graph with line breaks</p>4) Comments E.g. <!-- This is a comment --> Exercise 2: Insert more tags into the first HTML page

Html 5 10 l.jpg

HTML (5/10)

  • HTML Text FormattingStill remember the <b> … </b> tags? HTML uses the following tags to format a text:1) <big>, <small>, <em>, <i>, and <strong>2) <sub>, <sup>, <ins>, and <del>3) <code>, <kbd>, <samp>, <tt>, <var>, and <pre>4) <abbr>, <acronym>, <address>, <bdo>, <blockquote>, <q>, <cite>, and <dfn>Exercise 3: Try out <i>, <ins>, <del>, <sub>, and <sup> tags.Exercise 4: Try out the <bdo> tag with the attribute dir: <bdo dir="rtl">Exercise 5: Try to explain how the <pre> tag works.

Html 6 10 l.jpg

HTML (6/10)

  • HTML Character EntitiesRecall that the angel brackets have been used in HTML for special purpose, then how we can display < and > characters in a text? – Using Character Entities!A character entity has three parts: ampersand + entity name + semicolon, (i.e. &+…+;), e.g. &lt; &gt; &amp; &quot; &nbsp;Exercise 6: Try out the following character entities: &cent; &pound; &yen; &sect; &copy; &reg; &times; &divide;[Tip: character entities can be also presented by &+#+entity number+;e.g. &reg; is the same entity as &#174;]There is no need for us to memorize so many entities names!

Html 7 10 l.jpg

HTML (7/10)

  • HTML LinksThere must be Hyperlinks in a Hypertext. Two types of links are used in HTML: Href and Anchor.1) HTML uses the <a> tag to create a link to another document.2) <a> tag accepts href, name, and target as attributes e.g. <a href="" target="_blank">HWU</a> <a name="label">A label</a>3) To link directly to a labeled section, add a # sign and the name of the anchor to the end of a URL e.g. <a href="#label">Jump to the label</a>Exercise 7: An image as a link


<p>An image as a link:

<a href="">

<img border="0" src="" width="65" height="38">


Html 8a 10 l.jpg

HTML (8A/10)

  • HTML Forms

  • HTML Forms are used to select different kinds of user input.

  • A form is an area that can contain form elements.

  • Typical form elements: text fields, radio buttons, checkboxes, dropdown lists and so on.

  • Exercise 8: Try out the following form


<head><title>Personal Info</title>



<form method="POST" action="NONE">

<fieldset style="width: 413; height: 195; padding: 2">

<legend>Personal Info</legend>

Sex:Male<inputtype="radio" value="V1" checked name="R1">

Female<input type="radio" name="R1" value="V2"><br>

Html 8b 10 l.jpg

HTML (8B/10)

Birthday:<inputtype="text" name="T1" size="10" value="DD/MM/YYYY"><br>

Interests:Fictions<inputtype="checkbox" name="C1" value="ON">

Music<input type="checkbox" name="C2" value="ON">

Sports<input type="checkbox" name="C3" value="ON">

Shopping<input type="checkbox" name="C4" value="ON"><br>

Major:<select size="1" name="D1">

<option selected>Computer Science</option>






Any other comments:<br>

<textarea rows="6" name="S1" cols="54">

Less than 200 words please.</textarea><br>

<input type="submit" value=" OK " name="B1">

<input type="reset" value="Reset" name="B2"></fieldset></form>



Html 9 10 l.jpg

HTML (9/10)

  • Omitted: HTML Frames, Tables, Lists, Images, Colour, Background, Layout, Font, Events etc.

  • HTML StylesAll formatting info can be moved out of the HTML document and into a separate style sheet.

  • Internal & External Style SheetsAn external style sheet is ideal when the style is applied to many pages, whereas an internal style sheet should be used when a single document has a unique style. Internal styles are specified inside the <head> element of an HTML page. External styles are specified in a separate CSS file.

  • Cascading Style Sheets (CSS)When multiple style sheets coexist, they will cascade into one – thus CSS. Internal styles will “override” external ones.

Html 10 10 l.jpg

HTML (10/10)

  • SummaryIn this section we have quickly reviewed some rudimental HTML syntax and worked on a few practical exercises. The rest of this module requires you being able to create simple HTML pages, and more importantly, to understand other people’s HTML codes, which could be complex, especially HTML Forms and Form Elements.

Exercise 9: a CSS example

Contents21 l.jpg



HTML Fundamentals

Introduction to JavaScript

More Examples & Practices

A Brief Summary

Javascript 1 15 l.jpg

JavaScript (1/15)

  • Overview of JavaScript (JS)JS is the most popular scripting language that is supported by all major browsers, such as Internet Explorer, Mozilla, Firefox, Netscape, and Opera.

  • It is an interpreted (executes without preliminary compilation), lightweight programming language which was designed to add interactivity to traditional static HTML pages.

  • Usually, it is embedded directly into HTML pages, in order to generate dynamic texts, react to events, read and write HTML elements, validate data, and create cookies.

  • Basic JS is easy to understand, to learn, and to use. However, it doesn’t mean that JS is weak or restricted. Actually, it can be very competent and powerful at both the client side and the server side (examples available).

  • JS is completely free, so we can use it without purchasing a license.

NOTE: In this module, JS is only employed as a friendly approach to help you getting familiar with computer programming!

Javascript 2 15 l.jpg

JavaScript (2/15)

  • Integration of JS and HTMLTo insert a JavaScript into an HTML page, we use the <script> tag, e.g. <script type="text/javascript"> ... </script>

  • We can insert JS codes into either the <head> or the <body> section.

  • JS in the <body> section will be auto executed while the page loads.

  • JS in the <head> section will be executed only when they are called.

  • Exercise 1: The first JavaScript in the <body>/<head> section

<html><head><script type="text/javascript">

function message(){

alert("JS alert in the <head> section!")




<input onClick="message()" type="button" value="Click on me" name="B1">





<script type="text/javascript">

alert("JS alert in the <body> section!")


Javascript 3 15 l.jpg

JavaScript (3/15)

  • External JS codesSimilar to CSS, we can move all JS source codes out of our HTML and to an external .js file. For exercise 1, we can create a common text file using windows notepad with the following content:Then, rename the file to something.js, and call it in the HTML like this:

alert("JS alert in an external file!")

  • Content of the external script is identical to the previous example, except for the <script> tag.

  • It is very helpful to put JS codes into external files, if we would like to reuse the codes on many pages.





<script src=“something.js">




Javascript 4 15 l.jpg

JavaScript (4/15)

  • JavaScript SyntaxNOTE: Syntax VS. Semantics1) "The syntax of a language" refers to the rules that govern the way sentences are formed by the combination of lexical items into phrases.2) Semantics refers to the aspects of meaning that are expressed in a language, code, or other form of representation.3) While syntax is about the construction of complex signs from simpler signs, semantics is about the meaning of a specific sign in a system.4) Different languages may use different syntax (formats) to express the same semantics (meaning).5) When learning a programming language, it is necessary to above all acquire its syntax, but more importantly, we should always be clear about the semantics that is connotative.

Javascript 5 15 l.jpg

JavaScript (5/15)

  • JavaScript VariablesA variable is a "container" for information we want to store. We can refer to a variable by name to see or to change its value. JavaScript is a case-sensitive and weakly-typed programming language.

  • Variable names are case sensitive, and must begin with a letter or the underscore character.

  • We can create any variable with the var statement, regardless the actual type of the variable, e.g. var a_str = “12”; var a_int = 3.

  • One of the problems in weakly-typed languages is that it is not so clear what kind of result an operation would yield, e.g. in Visual Basic,a_str + a_int = 15, whereas in JavaScript, a_str + a_int = “123”.

  • A variable has its scope, or in other words, visibility. A variable declared within a function is called a local variable, which can only be accessed within that function. Contrarily, a variable declared outside a function is called a global variable, which can be accessed by all functions across the page.

Javascript 6 15 l.jpg

JavaScript (6/15)

  • JavaScript Operators Every programming language comes with a set of operators. Generally speaking, they are Arithmetic Operators, Assignment Operators, Comparison Operators, and Logical Operators.

  • Arithmetic Operators:+ Addition, - Subtraction, * Multiplication, / Division, % Modulus,++ Increment, -- Decrement. E.g. 5 % 2 = 1, 6 % 2 = 0NOTE: Some arithmetic operators can also be applied to strings.

  • Assignment Operators:=, +=, -=, *=, /=, %==?: e.g. a_variable = (condition) ? value1 : value2

  • Comparison Operators:==, !=, >, <, >=, <=, === (checks for both value and type)

  • Logical Operators:&& AND, || OR, ! NOT.

Javascript 7 15 l.jpg

JavaScript (7/15)

  • JavaScript Pop-up boxesJavaScript by default supports three kinds of popup boxes: Alert box, Confirm box, and Prompt box.

  • Alert - An alert box is used to make sureinformation comes through to the user,because when an alert box pops up, theuser will have to click "OK" to proceed.

  • Confirm - A confirm box is used if wewant the user to verify or accept something.If the user clicks "OK", the box returns true,otherwise false.

  • Prompt - A prompt box is used if we wantthe user to input a value before entering apage. If the user clicks "OK" the box returnsthe input value, otherwise null.

Javascript 8a 15 l.jpg

JavaScript (8A/15)

  • JavaScript FunctionsA function is a reusable code-block that will be executed by an event, or when the function is called.

  • The syntax for creating a function is:function function_name(var1, var2, … , varN) { some code }

  • var1, var2, etc are variables or values passed into the function. They are optional, and it is possible for us to define a non-parameter function.

  • The return statement is used to specify the value that is returned from the function. E.g.:function say_hi() { return “Hi!” }

Javascript 8b 15 l.jpg

JavaScript (8B/15)

Exercise 2: JavaScript Functions with Pop-up Boxes

<html><head><script type="text/javascript">

function disp_alert(){ alert("This is an alert box!" + '\n' + "Try out more other buttons!") }

function disp_confirm(){

var r=confirm("This is a confirm box!" + '\n' + "Please press a button...")

if (r==true){ document.write("You pressed OK!") }

else{ document.write("You pressed Cancel!") }


function disp_prompt(){

var name=prompt("This is a prompt box!" + '\n' + "Please enter your name...", "Mr. Bean")

if (name!=null && name!=""){ document.write("Hello " + name + "! How are you today?") }




<input type="button" onclick="disp_alert()" value="Display alert box" />

<input type="button" onclick="disp_confirm()" value="Display a confirm box" />

<input type="button" onclick="disp_prompt()" value="Display a prompt box" />


Javascript 9a 15 l.jpg

JavaScript (9A/15)

  • JavaScript Conditions In the previous exercise, we have used the if…else condition in JS. Another conditional statement available in JS is the switch statement.

  • Conditional statements are used to perform different actions for different decisions.

  • Syntax for the if…else statement is:if (condition){ code to be executed if condition is true } else{ code to be executed if condition is not true }

  • The if statement can be used solely without paired else statement.

  • Multiple if…else statements can be nested together (i.e. if…else if… else) to select one of many sets of lines to execute. E.g.:

Javascript 9b 15 l.jpg

JavaScript (9B/15)

<script type="text/javascript">

var d = new Date()

var time = d.getHours()

if (time<=10){ document.write("<b>Good morning!</b>") }

else if (time>10 && time<18){ document.write("<b>Good day!</b>") }

else{ document.write("<b>Good evening!</b>") }


  • On the other hand, we can use the switch statement to select one of many blocks of code to be executed. Syntax for the switch statement is:switch(n) { case 1: execute code block 1 break case 2: execute code block 2 break default: execute code block X if n is different from any cases listed above }

Javascript 9c 15 l.jpg

JavaScript (9c/15)

<script type="text/javascript">

//Note that Sunday=0, Monday=1, Tuesday=2, etc.

var d=new Date()


switch (theDay)


case 1:

document.write("The beginning of another tough week…")


case 5:

document.write("Finally, it’s Friday!!!")


case 6:

document.write("Super Saturday~~~")

break case 0: document.write("Sleepy Sunday…")


document.write("Common weekdays…")



Javascript 10a 15 l.jpg

JavaScript (10A/15)

  • JavaScript LoopsLoops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true.

1) for loop: used when we know in advance how many times the script should run. Syntax:for (var=startvalue; var<=endvalue; var=var+increment) { code to be executed }E.g.:

<html><body><script type="text/javascript">

var i=0

for (i=0;i<=10;i++)


document.write("Current value of i is " + i)

document.write("<br />")



Javascript 10b 15 l.jpg

JavaScript (10B/15)

2) while loop: used when we want the loop to execute and continue executing while the specified condition is true. Syntax:while (var<=endvalue) { code to be executed }E.g. the previous for loop can be implemented as the following while loop:

<html><body><script type="text/javascript">

var i=0

while (i<=10)


document.write("Current value of i is " + i)

document.write("<br />")




Javascript 10c 15 l.jpg

JavaScript (10C/15)

3) while loop continued: in a while loop if we want to execute a block of code at least ONCE even if the condition is false, and then continue executing while the specified condition is true, we could use a do…while loop. Syntax:do { code to be executed } while (var<=endvalue)E.g.:

<html><body><script type="text/javascript">

var i=0



document.write("Current value of i is " + i)

document.write("<br />")


}while (i<0)


Javascript 10d 15 l.jpg

JavaScript (10D/15)

4) break and continue: we can use these two special statements to break a loop or continue executing the code that follows after a loop. E.g.:

<html><body><script type="text/javascript">

var i=0

for (i=0;i<=10;i++)


if(i==3){ continue }

if(i==7){ breake }

document.write("Current value of i is " + i)

document.write("<br />")



5) for…in statement: used to iterate through the elements of an array or through the properties of an object (introduced later). Syntax:for (variable in object) { code to be executed }

Javascript 11 15 l.jpg

JavaScript (11/15)

  • JavaScript EventsEvents are actions that can be detected by JavaScript. Every element on a web page has certain events which can trigger JavaScript functions, e.g. the onClick event of a button to indicate that a function will run when a user clicks on the button.

  • Some typical events:

  • onload and onUnload: triggered when the user enters or leaves the page.

  • onFocus, onBlur and onChange: often used in combination with validation of form fields.

  • onSubmit: used to validate ALL form fields before submitting it.

  • onMouseOver and onMouseOut: often used to create "animated" buttons.

  • NOTE: More sophisticated events and JavaScript examples will be demonstrated in later sections, and for now, please just make sure that you understand the concept in general.

Javascript 12 15 l.jpg

JavaScript (12/15)

  • JavaScript Coding ConventionsSome other important things to know when scripting with JavaScript…

  • White Space - JavaScript ignores extra white spaces, so the following statements are equivalent to each other: 1) name = “Mr. Bean”2) name=“Mr. Bean”

  • Ending Semicolon - Unlike traditional programming languages, e.g. Java, C++, ending semicolons are optional in JS. However, they are required if you want to put more than one statement on a single line.

  • Break up a Code Line - We can break up a code line within a text string with a backslash, e.g. document.write("Hello \World!")

  • Comments - we can add single-line comments by using two slashes //, and multi-line comment blocks by using /* and */ - different from HTML comments!

  • Special Characters - we can insert special characters to a text string by using the backslash sign, e.g. \' (single quote) \" (double quote) \& (ampersand) \\ (backslash) \n (new line) \r (carriage return) and \t (tab).

Javascript 13a 15 l.jpg

JavaScript (13A/15)

  • JavaScript ObjectsJavaScript is an Object Oriented Programming (OOP) language, which allows us to define our own objects. An object is just a special kind of data that has its own properties (values associated with the object) and methods (actions that can be performed on objects).E.g.:


<script type="text/javascript">

var str="Hello world!"




  • document and str are objects

  • length is a property of str

  • write() is a method of document, and toUpperCase() is a method of str

In the next a few sections, we are going to have a look at some typical JS objects, such as String, Date, Boolean, Math, Array, and DOM.

Javascript 13b 15 l.jpg

JavaScript (13B/15)

  • String object - used to manipulate a stored piece of text.Related Property: length, returns the number of characters in a String.Related Methods: big(), small(), bold(), italics(), fontcolor(), fontsize(), sub(), sup()… valueOf(), toLowerCase(), toUpperCase()… charAt(), match(), replace(), substr(), substring()…Example:


<script type="text/javascript">

var str="Welcome to HWU!"

document.write(str.match("Welcome") + "<br />")

document.write(str.match("welcome") + "<br />")

document.write(str.match("Wel") + "<br />")

document.write(str.match("HWU!") + "<br />")



Javascript 13c 15 l.jpg

JavaScript (13C/15)

  • Date object – query at the Operating System for current date and timeRelated Methods: Date(), getDate(), getTime(), getDay(), getMonth(), getYear(), getHours(), getMinutes(), getSeconds(), getMilliseconds()…E.g.:

<html><head><script type="text/javascript">

function startTime(){

var today=new Date()

var h=today.getHours()

var m=checkTime(today.getMinutes())

var s=checkTime(today.getSeconds())


t=setTimeout('startTime()',500) }

function checkTime(i){

if(i<10){ i="0" + i }

return i }

</script></head><body onload="startTime()">

<div id="txt"></div>

<div><script type="text/javascript">document.write(Date())


Javascript 13d 15 l.jpg

JavaScript (13D/15)

  • Boolean object – used to convert a non-Boolean value to a Boolean value (true or false), i.e. an object wrapper for a Boolean value.Example:


<script type="text/javascript">

var b1=new Boolean(0)

var b2=new Boolean(1)

var b3=new Boolean("")

var b4=new Boolean(null)

var b5=new Boolean(NaN)

var b6=new Boolean("false")

document.write("0 is boolean "+ b1 +"<br />")

document.write("1 is boolean "+ b2 +"<br />")

document.write("An empty string is boolean "+ b3 + "<br />")

document.write("null is boolean "+ b4+ "<br />")

document.write("NaN is boolean "+ b5 +"<br />")

document.write("The string 'false' is boolean "+ b6 +"<br />")


Javascript 13e 15 l.jpg

JavaScript (13E/15)

  • Math object – enables us to perform common mathematical tasks.Related Properties: the Math object provides the following constantsE=2.718, LN2=0.693, LN10=2.302, LOG2E=1.414, LOG10E=0.434PI=3.14159, SQRT1_2=0.707, SQRT2=1.414Related Methods: abs(x), ceil(x), floor(x), exp(x), log(x), round(x), sqrt(x)… sin(x), cos(x), tan(x), asin(x), acos(x), atan(x), atan2(y,x)… max(x,y), min(x,y), power(x,y), random()…Example:


<script type="text/javascript">




Javascript 13f 15 l.jpg

JavaScript (13F/15)

  • Array object – used to store a set of values in a single variable name.Related Property: length, returns the number of elements in an array.Related Methods: concat(), join(), pop(), push(), reverse(), shift(), slice(), sort(), splice(), unshift()…E.g.:

<html><body><script type="text/javascript">

var arr = new Array(6)

arr[0] = "James Bond"

arr[1] = "Hugh Nisbet"

arr[2] = "Joe Smith"

arr[3] = "Zedong Mao"

arr[4] = "Bill Gates"

arr[5] = "Tonny Blare"

for (x in arr){

document.write(arr[x] + "<br />")


document.write("<br />" + arr.sort())


Javascript 13g 15 l.jpg

JavaScript (13G/15)

  • Document Object Model (DOM)DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML documents.All HTML elements, along with their containing text and attributes, can be accessed through the DOM - the contents can be modified or deleted, and new elements can be created. The HTML DOM is platform and language independent. It can be used by any programming language like Java, JavaScript, and VBScript.

  • Documentobject – DOM contains considerable numbers of objects, and in this module we just explain the Document object.Related Properties: the Document object contains some collection properties, such as anchors[], forms[], images[], and links[] that are in the document.There are also some simple properties, such as cookie, domain, lastModified, referrer, title, and URL.

Javascript 13h 15 l.jpg

JavaScript (13H/15)

Related Methods: open(), close(), write(), writeln()…getElementById(), getElementsByName(), getElementsByTagName()…E.g.:


<form id="Form1" name="Form1">

Your name: <input type="text">


<form id="Form2" name="Form2">

Your age: <input type="text">


<script type="text/javascript">

document.write("<p>The first form's name is: " + document.forms[0].name + "</p>")

document.write("<p>The second form's name is: " + document.getElementById("Form2").name + "</p>")


NOTE: HTML DOM is a very important W3C standard. If you are interested in web development, it would be necessary for you to know more about DOM objects!

Javascript 14a 15 l.jpg

JavaScript (14A/15)

  • JavaScript ApplicationsIn this section, we are going to enumerate some typical scenarios, in which JavaScript becomes very useful. Related source codes and example files are available at

  • Animation – Though originally JavaScript was introduced to add interactivity to HTML pages (i.e. to output dynamic contents), it has been widely used for creating animated texts and images.Nowadays, there are considerable numbers of JS Animation examples on the Internet – some may be intuitive, but some may not be. So, don’t worry if you have difficulty in understanding a particular piece of code. Most JS animations are tightly related to advanced web developing techniques, such as HTML DOM, CSS, and more complex JS syntax that is not covered by this module.Sometimes, it is better for us to temporally skip over a block of code, rather than struggling for a long time, parsing its exact meaning. Actually, it is more important and necessary to comprehend the overall structure of a JS program, so that we know how to reuse an existing piece of code.

Javascript 14b 15 l.jpg

JavaScript (14B/15)

  • Calendar – Previously, we have worked with JavaScript Date object. Now, let’s have a look at some other interesting calendar applications.

  • Action – JavaScript is an efficient scripting language. Usually, a useful action can be created just by a few lines of code. However, imagination and inspiration are crucial elements for any design.

  • Decoration – JavaScript is especially good at decorating plain HTML elements, such as texts, buttons, links, etc. Why not improve the attractiveness of your page by developing a unique JS widget for yourself?

  • Timing – So far, you may have found out that JavaScript Timing is often employed by the foregoing examples. With its help, we can execute some code not immediately after a function is called, but after a specified time interval.It's very easy to time events in JavaScript, because there are only two methods we need to know: 1) setTimeout() - executes a code some time in the future; 2) clearTimeout() - cancels the setTimeout().

Javascript 14c 15 l.jpg

JavaScript (14C/15)


Then, try out the Auto Scroll application which is more interesting.


<script type="text/javascript">

var c=0

var t

function timedCount(){





function stopCount(){




<input type="button" value="Start" onClick="timedCount()">

<input type="text" id="txt">

<input type="button" value="Stop" onClick="stopCount()">


Javascript 14d 15 l.jpg

JavaScript (14D/15)

  • Validation – JavaScript can be used to validate input data in HTML forms before sending off the content to a server.Form data that typically are checked by a JavaScript could be: 1) Has the user left required fields empty? 2) Has the user entered a valid e-mail address? 3) Has the user entered a valid date (e.g. DOB)? 4) Has the user entered text in a numeric field?E.g.:



<script type="text/javascript">

function validate_email(field, alerttxt)





if (apos<1||dotpos-apos<2) { alert(alerttxt);return false }

else { return true }



Javascript 14e 15 l.jpg

JavaScript (14E/15)

function validate_form(thisform)


with (thisform){

if (validate_email(email, "Not a valid e-mail address!")==false)

{ email.focus();return false }




<form action=" " onsubmit="return validate_form(this)" method="post">Email:<input type="text" name="email" size="30"><input type="submit" value="Submit">


  • Then, try out the Form Validation application, which does similar things, but using JavaScript Regular Expressions that is beyond the scope of this module.Extra free online materials on JavaScript programming:






Javascript 15 15 l.jpg

JavaScript (15/15)

  • Beyond JavaScript

  • CSSCascading Style Sheets provide a more effective and efficient way of controlling the style and layout of multiple web pages all at once!

  • DHTML & XHTMLDHTML is the art of combining a series of technologies (usually including JS, CSS, and XHTML) to create dynamic and interactive web sites. XHTML stands for Extensible Hyper Text Markup Language, which is basically a stricter and cleaner version of HTML, defined as an XML (beyond the scope of this module) application.

  • ASP, JSP, PHP, CGI, Servlet …Finally, because one of the most important objective for this module is to help the students start programming, it should be helpful for you to become aware of some well-known server-side programming technologies. On the one hand, it completes a panorama for the Client/Server architecture. And on the other hand, it provides an angle of view to the colourful world of Computer Science.

Contents54 l.jpg



HTML Fundamentals

Introduction to JavaScript

More Examples & Practices

A Brief Summary

More examples practices 1 3 l.jpg

More Examples & Practices (1/3)

  • Example 1 – Dummy Win2K Desktop

  • Description:

  • Windows 2000 is an operating system developed by Microsoft.

  • This example simulates a Win2K desktop environment with typical applications using pure JavaScript.

More examples practices 2 3 l.jpg

More Examples & Practices (2/3)

  • Example 2 – JavaScript StarCraft!!!

  • Description:

  • StarCraft (SC) is a real-time strategy game developed by Blizzard Entertainment.

  • This example simulates an SC playing session using pure JavaScript.

More examples practices 3 3 l.jpg

More Examples & Practices (3/3)

  • Practice – Apply JS to your project

  • Description:

  • Your project website might contain a form page for the users to submit personal information.

  • Develop necessary JS functions to verify your form entries.

  • If all entries have passed the verification, display the form contents to the user for a double check before final submission.

Contents58 l.jpg



HTML Fundamentals

Introduction to JavaScript

More Examples & Practices

A Brief Summary

Summary 1 2 l.jpg

Summary (1/2)

Module Contents

Overviewof CS

Introductionto JavaScript

Examples& Practices


Summary 2 2 l.jpg

Summary (2/2)

What isComputerScience

HTML &other Webdevelopmenttechnologies

Information & SkillsYou Should Obtained

Design &

implementationof JavaScriptapplications



of OOP &


in general

Slide61 l.jpg

Q & A

  • Any questions?

Fan Lu

School of Mathematical & Computer Science

Heriot-Watt University


Slide62 l.jpg

Thank You !

  • Login