0% found this document useful (0 votes)
13 views82 pages

Exploring JavaScript

Ebdfhttyfbfbcbbcbvbt hey ryytthfccc b hytyhfcfbbgfuuutbfbccbbchf he tried be bf bf jfbfbf he rujr if ycycj cc hfbfnchrhhfbfbfhfyccbfbcjdjrufyfjdkofy free owif

Uploaded by

skhulilena4
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)
13 views82 pages

Exploring JavaScript

Ebdfhttyfbfbcbbcbvbt hey ryytthfccc b hytyhfcfbbgfuuutbfbccbbchf he tried be bf bf jfbfbf he rujr if ycycj cc hfbfnchrhhfbfbfhfyccbfbcjdjrufyfjdkofy free owif

Uploaded by

skhulilena4
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
You are on page 1/ 82

Schools of Computing & Mathematical Sciences

Multimedia fundamentals 242

Exploring JavaScript
objectives
At the end of this unit you should be able to:
Display an understanding of the general concepts of the JavaScript
scripting language.

2
Introduction [1/2]
• JavaScript is used to add client-side dynamic functionality to websites.
• A pop up when the mouse hovers over an item in the browser, or new
text, colors, or images appearing on the page, or grabbing an object
on the page and dragging it to a new location, are some examples
of functionality that is implemented through JavaScript.
• JavaScript runs inside the browser and has direct access to all
elements of a web document.

3
Introduction [2/2]
• Contrary to popular misconception, JavaScript is not a spin-off of Java.
• Like PHP, JavaScript supports much of the structured programming
syntax used by the C programming language. JavaScript is also weakly
typed, which means a variable can easily be changed to a new type by
using it in a new context.
• With PHP experience, learning JavaScript is even easier.
• JavaScript is a core part of technologies that provide dynamic
frontends that web users expect.

4
JavaScript and HTML [1/5]
• JavaScript is a client-side scripting language that runs entirely inside
the web browser.
• To call it up, it is placed between opening <script> and closing
</script> HTML tags.
• A typical HTML 4.01 “Hello World” document using JavaScript might
look like as shown on the next slide

5
JavaScript and HTML [2/5]
Example: displaying “Hello World” using JavaScript

<html>
<head><title>Hello World</title></head>
<body>
<script type="text/javascript">
document.write("Hello World")
</script>
<noscript>
Your browser doesn't support or has disabled JavaScript
</noscript>
</body>
</html>

6
JavaScript and HTML [3/5]
• As shown in the previous example, document.write() is the equivalent
of PHP echo or print commands -it simply displays the supplied string
within the current document.
• Unlike PHP, there is no semicolon (;) at the end of document.write().
This is because in JavaScript, a newline serves the same purpose as a
semicolon. Having said that, if more than one statement is to be
written on a single line, then a semicolon must be placed after each
command except the last one.
• A semicolon can be added to the end of every statement, and
JavaScript will still work fine.

7
JavaScript and HTML [4/5]
The other thing to note in the previous "hello world" example is
the <noscript> and </noscript> pair of tags. These are used to offer
alternative HTML to users whose browser does not support JavaScript
or who have it disabled.

8
JavaScript and HTML [5/5]
• When the previous example is loaded, a web browser with JavaScript
enabled will output the following:

• A browser with JavaScript disabled will display this message:

9
Using scripts within a document head
• Besides placing a script within the body of a document, it can be
placed in the <head> section, and this is the ideal place if the script is
to be executed when a page loads.
• Placing critical code and functions in the <head> section, ensures that
they are ready to use immediately by any other script sections in the
document that relies on them.
• Another reason for placing a script in the document head is to enable
JavaScript to write things such as meta tags into the <head> section,
since the location of the script is the part of the document it writes to
by default.

10
Including JavaScript files [1/2]
• In addition to writing JavaScript code directly in HTML documents,
files of JavaScript code can be included either from the computer that
hosts the website or from anywhere on the Internet. The syntax for
this is as follows:
<script type="text/javascript" src="script.js"></script>
• To include a file from the Internet, use this:
<script type="text/javascript" src="http://someserver.com/script.js">
</script>

11
Including JavaScript files [2/2]
• The included script files themselves must not include any <script> or
</script> tags, because they are unnecessary: the browser already
knows that a JavaScript file is being loaded.
• Putting <script> ... </script> in the included JavaScript files will cause
an error.
• Including script files is the preferred method for using third-party
JavaScript files on a website.

12
Debugging JavaScript errors [1/9]
JavaScript handles error messages in a way that varies depending on
the browser used. The table below lists how to access JavaScript error
messages in each of the commonly used browsers:
Browser How to access JavaScript error messages
Mozilla Firefox Select Tools→Error Console or use the shortcut Ctrl-Shift-J on a PC, or Command-Shift-J on a Mac
Internet Explorer Select Tools→Internet Options→Advanced; then uncheck the Disable Script Debugging box and
check the “Display a Notification about Every Script Error” box.
Google Chrome Click the menu icon that looks like a page with a corner turned; then select Developer→JavaScript
Console. You can also use the shortcut Ctrl-Shift-J on a PC, or Command-Shift-J on a Mac.
Apple Safari Safari does not have an Error Console enabled by default, but you can turn it on by selecting
Safari→Preferences→Advanced→“Show Develop menu in menu bar.” However, you may prefer to
use the Firebug Lite JavaScript module, which many people find easier to use.

Opera Select Tools→Advanced→Error Console.


13
Debugging JavaScript errors [2/9]
NOTE: the way to access the JavaScript error message for a particular
browser described in the previous table may vary depending on the
version of the browser in use.
If your browser is not included in the table or the instructions are
incorrect, once you have figured out how to access the JavaScript error
messages for your browser, click the link below to add the information

https://docs.google.com/document/d/1C-5ltQD4ZncbUinuFe8B0GRqPi_M5LItRL5VgQkJN28/edit?usp=sharing

14
Debugging JavaScript errors [3/9]
Example: accessing the Error Console for Firefox 20.0

15
Debugging JavaScript errors [4/9]
Example: accessing JavaScript console on Google Chrome 36.0

16
Debugging JavaScript errors [5/9]
Here is an example of a script with an error:

<html>
<head><title>Hello World</title></head>
<body>
<script type="text/javascript">
document.write("Hello World)
</script>
</body>
</html>

17
Debugging JavaScript errors [6/9]
• Type the example (previous slide) and save it as test.html; then call it
up in your browser. It should succeed only in displaying the title, not
anything in the main browser window.
• When the Error Console is called up in the browser, it should display a
message such as:
SyntaxError: unterminated string literal
• Below the error message there will be a link to the source, which,
when clicked, shows the error line highlighted (but does not indicate
the exact position in the line at which the error was encountered)

18
Debugging JavaScript errors [7/9]
Example: Firefox 20.0 Error console

19
Debugging JavaScript errors [8/9]
Example: Google Chrome 36.0 JavaScript console:

20
Debugging JavaScript errors [9/9]
Additional JavaScript debugging support can be achieved by a browser
plug-in such as Firebug plug-in for Firefox and Chrome
(check it out at http://getfirebug.com )

21
Using comments
• To comment a single line, a pair of forward slashes are used like this:
//this is a comment

• Multiple lines can be commented by enclosing the lines between /*


and */ as illustrated below:

/* This is a section
of multiline comments
that will not be
interpreted */

22
Variables
Unlike PHP where variable names are identified by a dollar sign,
JavaScript variables do not start with any particular character. Variables
are named following these rules:
• A variable may include only the letters a-z, A-Z, 0-9, the $ symbol, and the
underscore (_).
• No other characters, such as spaces or punctuation, are allowed in a
variable name.
• The first character of a variable name can be only a-z, A-Z, $, or _ (no
numbers).
• Names are case-sensitive. Count, count, and COUNT are all different
variables.
• There is no set limit on variable name lengths.

23
String variables [1/2]
• JavaScript string variables should be enclosed in either single or
double quotation marks as shown below:
greeting = "Hello there"
warning = 'Be careful'

• A single quote can be included within a double-quoted string or a


double quote within a single-quoted string. But a quote of the same
type must be escaped by using the backslash character as illustrated
below:
greeting = "\"Hello there\" is a greeting"
warning = '\'Be careful\' is a warning'

24
String variables [2/2]
• To read from a string variable, it can be assigned to another one, like
this:
newstring = oldstring

• or it can be used in a function, like this:


status = "All systems are working"

document.write(status)

25
Numeric variables
• Numeric variables are created by assigning a value, like the example
below:
count = 42

temperature = 98.4

• Numeric variables can be read from and used in expressions and


functions just like strings.

26
Arrays [1/3]
• JavaScript arrays can contain string or numeric data, as well as other
arrays.
• To assign values to an array, use the following syntax (which in this
case creates an array of strings):
toys = ['bat', 'ball', 'whistle', 'puzzle', 'doll']

27
Arrays [2/3]
• To create a multidimensional array, smaller arrays are nested within a
larger one.
• For example, to create a two-dimensional array containing the colors of a
single face of a scrambled Rubik’s Cube (where the colors red, green,
orange, yellow, blue, and white are represented by their capitalized initial
letters), the following code could be used:
face =
[
['R', 'G', 'Y'],
['W', 'R', 'O'],
['Y', 'W', 'G']
]

28
Arrays [3/3]
• The previous example can also be written as follows:
face = [['R', 'G', 'Y'], ['W', 'R', 'O'], ['Y', 'W', 'G']]

• or even like this:


top = ['R', 'G', 'Y']
mid = ['W', 'R', 'O']
bot = ['Y', 'W', 'G']
face = [top, mid, bot]

• The element that is in row two and column three of this matrix, which is
the letter O can be accessed as follows (since array elements start at
position 0):
document.write(face[1][2])

29
Operators
Like PHP, operators in JavaScript, can involve mathematics, changes to
strings, and comparison and logical operations (and, or, etc.).

30
Arithmetic operators
Arithmetic operators are used to perform mathematics. They can be
used for the main four operations (addition, subtraction, multiplication,
and division) as well as to find the modulus (the remainder after a
division) and to increment or decrement a value.

31
Assignment operators
Assignment operators are used to assign values to variable. The table
below lists the various assignment operators available:

32
Comparison operators
Comparison operators are typically used inside a construct such as if
statement to compare two items. The table below lists the comparison
operators.

33
Logical operators
Unlike PHP, JavaScript’s logical operators do not include and and or
equivalents to && and ||, and there is no xor operator. The table
below lists the available logical operators.

34
Variable incrementing/decrementing
The following forms of post and pre-incrementing and decrementing
are supported by JavaScript:
++x
--y
x += 22
y -= 3

35
String concatenation
• JavaScript handles string concatenation slightly differently from PHP.
Instead of the . (period) operator, it uses the plus sign (+), as shown below:
document.write("You have " + messages + " messages.")
• If the variable messages is set to the value 3, the above code will output:
you have 3 messages.

• Just as a value can be added to a numeric variable with the += operator,


one string can be appended to another the same way:
name = "James"

name += " Dean"

36
Escaping characters [1/3]
• Escape characters, used to insert quotation marks in strings, can also
be used to insert various special characters such as tabs, newlines,
and carriage returns.
• For example, to use a tab to lay out the text can be done as follows:
heading = "Name\tAge\tLocation"
• In the above statement, the \t inserts a tab between the words.

37
Escaping characters [2/3]
Consider the following script:
<script type="text/javascript">
heading1 = "Name Age Location"
heading2 = "<pre>Name\tAge\tLocation</pre>"
heading3 = "<pre>Name\tAge\t\t\tLocation</pre>"
document.write(heading1)
document.write(heading2)

document.write(heading3)
</script>

38
Escaping characters [3/3]
The output of the program given in previous slide will look like the
figure below

39
JavaScript escape characters [1/2]

Character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Tab
\' Single quote (or apostrophe)
\" Double quote
\\ Backslash

40
JavaScript escape characters [2/2]

Character Meaning
\XXX An octal number between 000 and 377 that represents the Latin-1 character
equivalent (such as \251 for the© symbol)
\xXX A hexadecimal number between 00 and FF that represents the Latin-1 character
equivalent (such as \xA9 forthe © symbol)
\uXXXX A hexadecimal number between 0000 and FFFF that represents the Unicode
character equivalent (such as \u00A9 for the © symbol)

41
<intentionally left blank>

42
Variable typing [1/3]
• Like PHP, JavaScript is a loosely typed language; the type of a variable is
determined only when a value is assigned and can change as the variable
appears in different contexts.
• Consider the following example:
<script>
n = '838102050' // Set 'n' to a string
document.write('n = ' + n + ', and is a ' + typeof n + '<br>')
n = 12345 * 67890; // Set 'n' to a number
document.write('n = ' + n + ', and is a ' + typeof n + '<br>')

n += ' plus some text' // Change 'n' from a number to a string


document.write('n = ' + n + ', and is a ' + typeof n + '<br>')
</script>

43
Variable typing [2/3]
In this example (previous slide):
1. The variable n is assigned the string value 838102050, the next line
prints out its value, and the typeof operator is used to look up the
type.
2. n is given the value returned when the numbers 12345 and 67890
are multiplied together. This value is also 838102050, but it is a
number, not a string. The type of variable is then looked up and
displayed.
3. Some text is appended to the number n and the result is displayed.

44
Variable typing [3/3]
• The output from this script (previous code snippet) looks like this:
n = 838102050, and is a string
n = 838102050, and is a number
n = 838102050 plus some text, and is a string
• The typeof operator can be used to look up a variable's type. To ensure that
a variable has a particular type, it can be forced to that type by using
statements such as the following:
n = "123"
n *= 1 // Convert 'n' into a number

n = 123
n += "" // Convert 'n' into a string

45
<intentionally left blank>

46
Functions
• As with other programming languages, JavaScript functions are used to
separate out sections of code that perform a particular task.
• To create a function, declare it in the manner shown below:
<script>
function product(a, b)
{
return a*b
}

</script>
• This function takes the two parameters passed, multiplies them together,
and returns the product
47
Global variables
• Global variables are variables defined outside of any functions (or
within functions but defined WITHOUT the var keyword). They can be
defined in the following ways:

a = 123 // global scope


var b = 456 // local scope
if (a == 123) var c = 789 // local scope
• Regardless of whether the var keyword is used, as long as a variable is
defined outside of a function, it is global in scope, which means that
every part of a script can have access to it.

48
Local variables [1/5]
• Parameters passed to a function automatically have local scope; that
is, they can be referenced only from within that function.
• However, there is one exception: arrays are passed to a function by
reference, so if any elements in an array parameter are modified, the
elements of the original array will be modified.
• A local variable that has scope only within the current function, and
has NOT been passed as a parameter, can be defined using the var
keyword.
• The next slide shows a function that creates one variable with global
scope and two with local scope.
49
Local variables [2/5]
<script>
function test()
{
a = 123 // Global scope
var b = 456 // Local scope
if (a == 123) var c = 789 // Local scope
}
</script>

50
Local variables [3/5]
• To test whether scope setting has worked in PHP, the isset function
can be used. However, JavaScript does not have the isset function, so
the typeof operator is used, which returns the string undefined when
a variable is not defined.
• The next slide shows an example script that uses the typeof operator
to check the scope of the variables defined in the function test ()

51
Local variable [4/5]

<script>
test()

if (typeof a != 'undefined') document.write('a = "' + a + '"<br>')


if (typeof b != 'undefined') document.write('b = "' + b + '"<br>')
if (typeof c != 'undefined') document.write('c = "' + c + '"<br>')

function test()
{
a = 123
var b = 456
if (a == 123) var c = 789
}
</script>

52
Local variable [5/5]
• The output from this script is the following single line:
a = "123"
• This shows that only the variable a was given global scope, which is
exactly what we would expect, since the variables b and c were given
local scope by being prefaced with the var keyword.

53
<intentionally left blank>

54
The Document Object Model [1/8]
• JavaScript is built around the Document Object Model (DOM).
• DOM breaks down the parts of an HTML document into discrete
objects, each with its own properties and methods that can be
controlled via JavaScript.
• JavaScript separates objects, properties, and methods by using . (a
period). For example, consider an object named card with properties
such as name, address, phone number, etc. The syntax would look like
card.name
card.phone
card.address

55
The Document Object Model [2/8]
• To invoke a method that displays the properties of object card,
the syntax to use might look as shown below
card.display()
• Looking back at examples where the document.write () statement was
used, it should be apparent at this stage that actually, write () is a
method of the document object.
• Within JavaScript, there is a hierarchy of parent and child objects,
which is what is known as the Document Object Model.

56
The Document Object Model [3/8]
Example of the DOM object hierarchy

57
The Document Object Model [4/8]
• The figure (previous slide) uses HTML tags to illustrate the
parent/child relationship between the various objects in a document.
• For example, a URL within a link is part of the body of an HTML
document. The JavaScript syntax to reference the URL is like this:
url = document.links.linkname.href
• Notice in the previous figure how this follows the central column
down. The first part, document, refers to the <html> and <body> tags;
links.linkname refers to the <a> tag; and href to the href attribute.

58
The Document Object Model [5/8]
• The next slide gives an example of a script that reads a link's
properties.
• Type it in, save it as linktest.html, then call it up in your browser.

59
The Document Object Model [6/8]
Reading a link URL with JavaScript:

<html>
<head>
<title>Link Test</title>
</head>
<body>
<a id="mylink" href="http://mysite.com">Click me</a><br>
<script type="text/JavaScript">
url = document.links.mylink.href
document.write('The URL is ' + url)
</script>
</body>
</html>
60
The Document Object Model [7/8]
• The figure below shows the output of linktest.html.
• The first line of output comes from the hyperlink created using
<a id="mylink" href="http://mysite.com">Click me</a><br>

• The second line of output comes from the document.write () method


as shown in the previous slide.

61
The Document Object Model [8/8]
NOTE
The previous example may not work if using Internet Explorer
(depending on the version of Internet Explorer). This is because
Microsoft’s implementation of JavaScript, called JScript, has some
subtle differences from the recognized standards. To fix the issue, try
replacing the line:
url = document.links.mylink.href
with the following:
url = document.getElementById('mylink').href

62
Another use for the $ symbol [1/2]
• As already pointed out, the $ symbol is allowed in JavaScript variable
and function names.
• Some programmers have decided that the getElementById function is
so prevalent in JavaScript that they have written a function to replace
it called $ as shown below:

<script>
function $(id)
{
return document.getElementById(id)
}
</script>
63
Another use for the $ symbol [2/2]
• With the $ function in place, syntax such as
document.getElementById('mylink').href
can be replaced by
$('mylink').href
• Because of this, strange-looking code as shown below, may be
encoutered:
url = $('mylink').href

64
<intentionally left blank>

65
Using the DOM [1/4]
• The links object is actually an array of URLs, so the mylink URL in the
previous example can be referred to in the following way (because it
is the first, and the only link):
url = document.links[0].href
• To determine how many links are there in the entire document, the
length property of the links object can be queried as illustrated
below:
numlinks = document.links.length

66
Using the DOM [2/4]
• Using the length propery of the links objects, all links in the
documents can be extracted and displayed like this:
for (j=0 ; j < document.links.length ; ++j)
document.write(document.links[j].href + '<br>')

• The length of something is a property of every array, and many


objects as well. For example, the number of items in the web
browser’s history can be queried like this:
document.write(history.length)

67
Using the DOM [3/4]
• However, to prevent websites from snooping on someone's browsing
history, the history object stores only the number of sites in the array:
these values cannot be read from or written to.
• However, the current page can be replaced with one from the history,
if the position it has within the history is known.
• Replacing the current page can be very useful in cases in which it is
known that certain pages in the history came from your site, or you
simply wish to send the browser back one or more pages, which is
done with the go () method of the history object.

68
Using the DOM [4/4]
• For example, to send the browser back three pages, the following
command can be issued:
history.go(-3)
• The following methods can also be used to move back or forward a page at
a time:
history.back()
history.forward()
• Similarly, the currently loaded URL can be replaced with any URL, like this:
document.location.href = 'http://google.com'

69
<intentionally left blank>

70
Using console.log [1/4]
• JavaScript provides several quick and easy ways to display results of
expressions.
• The console.log function outputs the result of any value or expression
passed to it in the console of the current browser.
• The browser console is a special mode with a frame or window
separate to the browser window, and in which errors and other
messages can be made to display.
• Calling up the console is not ideal for beginners because it is different
in all browsers, it works differently in different browsers, and the
output is not near the web content in the browser.
71
Using console.log [2/4]
• Consider the following code:

<script type="text/javascript">
console.log("hello world")
</script>

• In Firefox for example, the console.log () function sends the output to


the Web console, which can be launched by clicking the Firefox menu
and selecting Web Developer>Web Console as shown in the next slide.

72
Using console.log [3/4]
Opening the Web console in Firefox

73
Using console.log [4/4]
To view the output of the console.log () function in Firefox Web
console:

74
Using alert [1/2]
• The alert () function displays values or expressions passed to it in a
pop-up window, which requires the user to click a button to close.
• Below is a simple example usage of the alert () function.

<script type="text/javascript">
alert("hello world")
</script>

75
Using alert [2/2]
• The figure below shows the output of the alert () function example.
• Pop-up windows can become quite irritating very quickly for users.
• Alerts have the additional downside of displaying only the current
message -previous ones are erased.

76
Writing into elements [1/3]
• It is possible to write directly into the text of an HTML element, which
is a fairly elegant solution (and the best one for production websites).
• To do that would require such an element to be created, and some
lines of JavaScript code to access it.
• The resulting code is cumbersome and confusing. For this reason, this
course does not focus on writing into HTML elements because the
additional code would get in the way of the core concepts that the
course aims to cover.

77
Writing into elements [2/3]
Example:

<html>
<body>

<p id="p1">Hello World!</p>

<script>
document.getElementById("p1").innerHTML = "New text!";
</script>

</body>
</html>

78
Writing into elements [3/3]
Output

79
Using document.write [1/2]
• The document.write () function writes a value or expression at the
current browser location, and is therefore a good choice for quickly
displaying results, because it keeps all the examples short and clear,
by placing the output right there in the browser next to the web
content and code.
• Some developers consider the document.write () function unsafe,
because when it is called after a web page is fully loaded, it will
overwrite the current document. While this is correct, it does not
apply to any of the examples in this course, because they all use
document.write the way it was originally intended; as part of the
page creation process, calling it only before the page has completed
loading and displaying.
80
Using document.write [2/2]
• However, although this course uses document.write in this way for
simple examples, note that it may not always be appropriate in
production code.
• Instead, the preceding option of writing directly into a specially
prepared HTML elements, should be used.
• So please remember that where you see document.write being called
in code examples for this course, it is there primarily to simplify an
example.

81
End

82

You might also like