~~SLIDESHOW~~
Contact Hour 7: To be discussed on Tuesday 11th February, 2013.
Lecturer: Dr Chris P. Jobling.
JavaScript is the most commonly used language for achieving interactivity on the client side of a Web Application. It allows the browser to be scripted to enable interactive effects to be achieved without requiring a round-trip to the web server.
These slides and notes were originally based on Chapter 4 of Robert W. Sebasta, Programming the World-Wide Web, 3rd Edition, Addison Wesley, 2006. with additional examples and explanation from Chris Bates, Web Programming: Building Internet Applications, 3rd Edition, John Wiley, 2006.
Some of the examples are taken from the ABC of JavaScript: An Interactive JavaScript tutorial provided by OpenJS.
We will also illustrate the examples using the JavaScript console provided in the Firebug extension for Mozilla Firefox.
This lecture gives a quick tour of the basics of JavaScript, introducing its most important concepts and constructs but leaving out many of the details of the language.
Contents of this Lecture
Don't forget to consider these as the basis for your PeerWise quizzes
At the end of this lecture you should be able to answer these questions:
At the end of this lecture you should be able to answer these questions:
At the end of this lecture you should be able to answer these questions:
undefined
?true
or false
?typeof
return for an object
operand?At the end of this lecture you should be able to answer these questions:
document.write
?alert
?console.log
?prompt
method.<note> JavaScript is explicitly prohibited from accessing the local file store: it cannot write to the local hard drive nor read from it!
Unfortunately the implementation of DOM (a W3C standard) varies between browsers, so this is the main area that causes incompatibilities when writing JavaScript programs. </note>
JavaScript is a functional programming language.
JavaScript is NOT an object-oriented programming language
<note>
prototype-based inheritance – the new
operator creates an instance of an object in which all properties are created and assigned to that object. Adding or removing properties has no effect on other instances of the same object that may exist at the same time. There is no possibility of a class variable that is shared by all objects
</note>
JavaScript has a number of big benefits to anyone who wants to make their web site dynamic:
Although JavaScript looks like it should be a win-win for both developers and users, this is not always the case:
function describe() { var major = parseInt(navigator.appVersion); var minor = parseFloat(navigator.appVersion); var agent = navigator.userAgent.toLowerCase(); document.write("<h1>Details in Popup</h1>"); document.close(); window.alert(agent + " " + major); }
function farewell() { window.alert("Farewell and thanks for visiting"); }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head>...</head> <body> <div class="container"> <h1>Our first JavaScript script</h1> : <div id="result"><!-- Result will be appended to this div--></div> <a href="../index.html" onclick="farewell();">Back to examples</a> : </div> <script language="javascript" type="text/javascript"> //<![CDATA[ <!-- // Get details of browser // Say goodbye // --> // ]]> </script> </body> </html>
There are some comments needed to explain this!
Firstly, the <script>
element requires two attributes: the type attribute is the MIME-type for JavaScript files text/javascript
; and language defines the language of the scripting language. These would seem to be equivalent but they are used for different purposes. The type attribute informs the browser what the content of the script tag is expected to be JavaScript code (particularly important if the script is uploaded from a file and the Web server does not properly identify the content as JavaScript). The language attribute tells the Browser to interpret the script with a JavaScript interpreter (it is possible, though probably not portable, to have other languages such as Perl, Python, TCL and for Internet Explorer VBScript).
Secondly, it is important that the script-code be protected from the HTML interpreter. In XML, the standard way to do this is to embed non-xml code in the <![CDATA[ … ]]>
tags. This basically ensures that code symbols that would be special to XML (e.g. quotation marks, <
, >
, &
) need not be replaced by character entities. For older versions of HTML, we need to use the HTML comment block to comment the script code <!– … –>
. Finally, we need to protect XML/HTML from the scripting language itself by using script comment markers, e.g: //<![CDATA[, // –>, // ]]>
.
<note>If you feel that this attention to detail is more than you want to deal with, it's worth noting that, as for CSS, a lot of these details disappear if the script is loaded from a separate file!</note>
<!DOCYPE html> <html lang="en"> <head>....</head> <body> <div class="container"> <h1>Our first JavaScript script</h1> : <div id="result"><!-- Result will be appended to this div--></div> <a href="../index.html" onclick="farewell();">Back to examples</a> : </div> <script> // Get details of browser // Say goodbye </script> </body> </html>
This is much simpler because:
language
or the type
attributes in the script
tag.CDATA
block is only needed when the script is being used within the XML serialization of HTML5.
The script itself defines the two functions describe()
and farewell()
. Function describe()
is called when the document is loaded by the browser as defined by the onload
attribute of the <body>
element. Similarly, farewell()
is called when the link “Back to examples” is clicked. This causes a click event to happen and the onclick
attribute of the link causes farewell()
to be called7). The attributes onload
and onclick
are two of the standard events that can be defined in HTML and which provide the simplest (although discouraged) way to communicate from the document to the script. We will describe many more later.
Run the script.
Here is the script in full:
<!DOCTYPE html> <!-- hello_js_world.html: An Example JavaScript script --> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Our first JavaScript script</title> <meta name="viewport" content="width=device-width"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/bootstrap-responsive.min.css"> <link rel="stylesheet" href="css/main.css"> <script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script> </head> <body onload="describe()"> <!--[if lt IE 7]> <p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</p> <![endif]--> <div class="container"> <h1>Our first JavaScript script</h1> <p>Use this file as a template for your own. <div id="result"></div> <a href="../index.html" onclick="farewell();">Back to examples</a> <hr> <footer> <p>© Swansea University 2013</p> </footer> </div> <!-- /container --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.0.min.js"><\/script>')</script> <script src="js/vendor/bootstrap.min.js"></script> <script src="js/plugins.js"></script> <script> // The actual JavaScript code goes here // Define point in DOM where result will be appended as HTML var result_element = $('#result'); function describe() { var major = parseInt(navigator.appVersion); var minor = parseFloat(navigator.appVersion); var agent = navigator.userAgent.toLowerCase(); result_element.append("<h2>Details in Popup<\/h3>"); window.alert(agent + " " + major); } function farewell() { window.alert("Farewell and thanks for visiting"); } </script> </body> </html>
Please note that most of this is required by the Twitter Bootstrap template. You should pay attention to the final script element. A small amount of jQuery magic
has been used to avoid the destructive use of the document.write
method to write the text Details in Popup into the document.
<script> -- JavaScript script - </script>
<script>
, as in <script src = "myScript.js"></script>
At least 3 ways:
<script>
tags or link code to <script>
tags in an HTML page. Reload page to execute.Provided by jsFiddle. Use this and the developer tools console to play with JavaScript.
$
) or underscore (_
), followed by any number of letters, underscores, dollar signs and digits//
and /* . . . */
The 25 reserved words of JavaScript are illustrated in the table below.
break | delete | function | return | typeof |
case | do | if | switch | var |
catch | else | in | this | void |
continue | finally | instanceof | throw | while |
default | for | new | try | with |
Number
, String
, and Boolean
)'
or "
\t
)true
and false
null
undefined
var sum = 0 today = "Monday" flag = false;
In this example the variable sum
is declared explicitly by use of the var
keyword, whereas the variables today
and flag
are declared implicitly. If the variables do yet yet exist they will be created and assigned the values that appear on the right-hand side of the assignment =
. If a variable already exists, it will take on the new value even if the value is a different type from the variable that was previously assigned.
<note>
Please note that modern usage is to explicitly declare all variables using var
before they are used. If you don't JavaScript will make the variable global and this will often cause unexpected behaviour! Modern style would declare the examples above8):
var sum = 0, today = "Monday", flag = false;
</note>
Visit Chapter 2 of Eloquent JavaScript.
++
, –
, +
, -
, *
, /
, %
Math
object provides floor
, round
, max
, min
, trig functions, etc. e.g., Math.cos(x)
MAX_VALUE
, MIN_VALUE
, NaN
, POSITIVE_INFINITY
, NEGATIVE_INFINITY
, PI
Number.MAX_VALUE
NaN
NaN
is not equal to any number, not even itself NaN == NaN
is always false
!isNaN(x)
toString
which converts number to a string.+
+
) coerce strings to numbers (if either operand of +
is a string, it is assumed to be concatenation)NaN
toString
method of numbersparseInt
and parseFloat
on stringslength
e.g., var len = str1.length;
(a property)charAt(position)
e.g., str.charAt(3)
indexOf(string)
e.g., str.indexOf('B')
substring(from, to)
e.g., str.substring(1, 3)
toLowerCase()
e.g., str.toLowerCase()
typeof
operator“number”
, “string”
, or “boolean”
for primitives“object”
for objects, null
for Null, and “undefined”
for UndefinedtoLocaleString
– returns a string of the dategetDate
– returns the day of the monthgetMonth
– returns the month of the year (0—11)getDay
– returns the day of the week (0—6)getFullYear
– returns the yeargetTime
– returns the number of milliseconds since January 1, 1970getHours
– returns the hour (0—23)getMinutes
– returns the minutes (0—59)getMilliseconds
– returns the millisecond (0—999)document
and window
, which refer to the Document and Window objects, respectivelywrite
, which dynamically creates (HTML) contentdocument.write("Answer: " + result + "<br />");
<br />
, but not \n
)console.log
9) function.In Firefox and Chrome developer tools there is a JavaScript console. You can write to it using:
console.log("Answer: " + result);
It's better than document.write
because as well as outputting string versions of its arguments, it will actually output objects that you can browse.
<div id="result"> </div>
$('#result').append('<p>The html you would have written with <code>document.write()
</p>'); </code>
<div id="result"> <p>The html you would have written with <code>document.write()
</p> </div> </code>
alert
, confirm
, and prompt
alert(“Hey! \n”);
Boolean (yes,no: true/false):
confirm(“Do you want to continue?”);
Strings:
prompt(“What is your name?”, “”);
OK
and Cancel
OK
without typing a response in the text box (waits for OK
)
You can only enter a string this way but by use of coercion, or better still the parseInt
and parseFloat
functions, you can convert strings to numbers.
<!DOCTYPE html> <!-- roots.html Compute the real roots of a given quadratic equation. If the roots are imaginary, this script displays NaN, because that is what results from taking the square root of a negative number --> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Real roots of a quadratic equation</title> <meta name="viewport" content="width=device-width"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/bootstrap-responsive.min.css"> <link rel="stylesheet" href="css/main.css"> <script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script> </head> <body> <!--[if lt IE 7]> <p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</p> <![endif]--> <div class="container"> <h1>Real roots of a quadratic equation</h1> <p>Use this file as a template for your own JavaScript experiments. <div id="result"><!-- Result will be appended to this div--></div> <a href="../index.html">Back to examples</a> <hr> <footer> <p>© Swansea University 2013</p> </footer> </div> <!-- /container --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.0.min.js"><\/script>')</script> <script src="js/vendor/bootstrap.min.js"></script> <script src="js/plugins.js"></script> <script> // The actual JavaScript code goes here // Declare variables we'll be using var result_element, a, b, c, root_part, denom, root1, root2; // Find point in DOM where result will be appended as HTML result_element = $('#result'); // Get the coefficients of the equation from the user a = prompt("What is the value of 'a'? \n", "1"); b = prompt("What is the value of 'b'? \n", "3"); c = prompt("What is the value of 'c'? \n", "2"); // Compute the square root and denominator of the result root_part = Math.sqrt(b * b - 4.0 * a * c); denom = 2.0 * a; // Compute and display the two roots root1 = (-b + root_part) / denom; root2 = (-b - root_part) / denom; // Display results in page result_element.append("<p>The first root is: " + root1 + "<br />"); result_element.append("The second root is: " + root2 + "</p>"); </script> </body> </html>
This is the key bit:
// Declare variables we'll be using var result_element, a, b, c, root_part, denom, root1, root2; // Find point in DOM where result will be appended as HTML result_element = $('#result'); // Get the coefficients of the equation from the user a = prompt("What is the value of 'a'? \n", "1"); b = prompt("What is the value of 'b'? \n", "3"); c = prompt("What is the value of 'c'? \n", "2"); // Compute the square root and denominator of the result root_part = Math.sqrt(b * b - 4.0 * a * c); denom = 2.0 * a; // Compute and display the two roots root1 = (-b + root_part) / denom; root2 = (-b - root_part) / denom; // Display results in page result_element.append("<p>The first root is: " + root1 + "<br />"); result_element.append("The second root is: " + root2 + "</p>");
Getting started with JavaScript
Don't forget to consider these as the basis for your PeerWise quizzes
At the end of this lecture you should be able to answer these questions:
At the end of this lecture you should be able to answer these questions:
At the end of this lecture you should be able to answer these questions:
undefined
?true
or false
?typeof
return for an object
operand?At the end of this lecture you should be able to answer these questions:
document.write
?alert
?console.log
?prompt
method.There are many more review questions available.
The Introduction and the opening of Chapter 1 of Eloquent JavaScript cover much the same material as these notes and include some interactive exercises that you can try.
Write, test and debug (if necessary) HTML5 files that include JavaScript scripts for the following problems. When required to write functions, you must include a script to test the function with at least two different data sets.
console.log
for output.Math.max
.Programming in JavaScript
onunload
on the body tag to calle farewell(). This doesn't work with modern browsers because they typically prevent pop-ups when a page us unloaded (i.e. reloaded or replaced by another document) because of the annoying way that unscrupulous website owners would use pop-ups to direct you to another site when trying to leave.