~~SLIDESHOW~~ ====== Getting Started with JavaScript ====== **Contact Hour 7**: To be discussed on Tuesday 11th February, 2013. **Lecturer**: [[C.P.Jobling@Swansea.ac.uk|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 [[http://www.openjs.com/tutorials/basic_tutorial/index.php|ABC of JavaScript: An Interactive JavaScript]] tutorial provided by [[http://www.openjs.com/|OpenJS]]. We will also illustrate the examples using the JavaScript console provided in the Firebug extension for Mozilla Firefox. ===== Getting started with JavaScript ===== 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** * [[eg-259:lecture5#overview_of_javascript|Overview of JavaScript]] * [[eg-259:lecture5#object_orientation_and_javascript|Object Orientation and JavaScript]] * [[eg-259:lecture5#general_syntactic_characteristics|General Syntactic Characteristics]] * [[eg-259:lecture5#primitives_operations_and_expressions|Primitives, Operations, and Expressions]] * [[eg-259:lecture5#screen_output_and_keyboard_input|Screen Output and Keyboard Input]] ===== Learning Outcomes (1) ===== **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//: - Describe briefly three major differences between Java and JavaScript. - Describe briefly three major uses of JavaScript on the client side. - Describe briefly the basic process of event-driven computation. - What are the two categories of properties in JavaScript? - Describe the two ways to embed a JavaScript script in an HTML document. ===== Learning Outcomes (2) ===== //At the end of this lecture you should be able to answer these questions//: - What are the advantages and disadvantages of JavaScript? - What are the two forms of JavaScript components? - What are the five primitive data types in JavaScript? - Do single-quoted string literals have any different characteristics than double-quoted string literals? ===== Learning Outcomes (3) ===== //At the end of this lecture you should be able to answer these questions//: - In what circumstances would a variable have the value ''undefined''? - If the value undefined is used as a Boolean expression, is it interpreted as ''true'' or ''false''? - What value does ''typeof'' return for an ''object'' operand? ===== Learning Outcomes (4) ===== //At the end of this lecture you should be able to answer these questions//: - What is the usual end-of-line punctuation for the string operand to ''document.write''? - What is the usual end-of-line punctuation for the string operand to ''alert''? - What is the usual end-of-line punctuation for the string operand to ''console.log''? - Describe the operation of the ''prompt'' method. ===== Overview of JavaScript ===== * Originally developed by Netscape, as //LiveScript// * Became a joint venture of Netscape and Sun in 1995, renamed //JavaScript// * Now standardized by the European Computer Manufacturers Association as [[http://www.ecma-international.org/publications/standards/Ecma-262.htm|ECMA-262]] (also ISO 16262) * We'll call collections of JavaScript code //scripts//, not //programs// ===== Java and JavaScript ===== * JavaScript and Java are only related through syntax * JavaScript is dynamically typed * JavaScript's support for objects is very different ===== Applications of JavaScript ===== * JavaScript can be used to replace some of what is typically done with applets (including graphics((Graphics support via the new //Canvas// feature and associated JavaScript APIs was added in HTML 5 and is available in all modern browsers))) * JavaScript can be used to replace some of what is done with CGI (including limited file operations and networking) * User interactions through forms are easy * The //Document Object Model// (DOM) makes it possible to support dynamic HTML documents with JavaScript * Many of the new features added to HTML5 are actually JavaScript features! ---- 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. ===== Event-Driven Computation ===== * User interactions with HTML documents in JavaScript use the event-driven model of computation * User interactions with HTML elements can be used to trigger execution of scripts ===== Object Orientation and JavaScript ===== JavaScript is a //functional// programming language. JavaScript is **NOT** an object-oriented programming language * JavaScript does not support class-based inheritance * JavaScript does not support polymorphism * JavaScript has //prototype-based inheritance//, which is much different ---- //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 ===== JavaScript Objects ===== * JavaScript objects are collections of properties, which are like the members of classes in Java and C++ * JavaScript has primitives for simple types * The root object in JavaScript is //Object// -- all objects are derived from Object((//Object// has no properties!)) * All JavaScript objects are accessed through references * Properties can be object references, primitives or //functions// * Properties can be added and deleted at any time! ===== Benefits of JavaScript ===== JavaScript has a number of big benefits to anyone who wants to make their web site dynamic: * It is widely supported in Web browsers. * It gives easy access to the document objects (elements and attributes) and can manipulate most of them. * It can give interesting animations without the long download times associated with many multimedia data types. * It is relatively secure.((JavaScript can neither read from the your local hard drive nor write to it and you cannot get a virus infection directly from JavaScript.)) * Web surfers do not need a special plug-in to use your scripts ===== Problems with JavaScript ===== Although JavaScript looks like it should be a win-win for both developers and users, this is not always the case: * Most scripts rely upon manipulating elements of the DOM. Support for a standard set of DOM objects currently does not exist((Although the situtaion is much better now as HTML5 is more prescriptive about what the DOM should be and what browsers should do in given situations.)) and access to objects differs from Browser to Browser. * If your script does not work then your web page is useless! * Because of the problems of broken scripts, many Web surfers disable JavaScript support in their browser. * Scripts can run slowly and complex scripts take a long time to start up((Again modern browser developers have put a lot of effort into making script engines more efficient. Conversely, web applications rely more and more on scripts, so this speed advantage may not last long)). * To overcome browser issues, modern developers make use of libraries that provide better abstractions of the DOM and allow separation of concerns between the application data and the display of that data in HTML((Two popular libraries are jQuery and BackboneJS.)) ===== A Simple Script (1) ===== * Get details of browser function describe() { var major = parseInt(navigator.appVersion); var minor = parseFloat(navigator.appVersion); var agent = navigator.userAgent.toLowerCase(); document.write("

Details in Popup

"); document.close(); window.alert(agent + " " + major); }
===== A Simple Script (2) ===== * Say goodbye function farewell() { window.alert("Farewell and thanks for visiting"); } ===== Script in XHTML ===== ...

Our first JavaScript script

:
Back to examples :
---- There are some comments needed to explain this! Firstly, the '' ---- This is much simpler because: - JavaScript is the default so we do not have to specify the ''language'' or the ''type'' attributes in the ''script'' tag. - Modern browsers don't need the protection of HTML comments to prevent their intrepretation by the browser - The ''CDATA'' block is only needed when the script is being used within the //XML serialization of HTML5//. ===== The Script Itself ===== 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 '''' 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 called((The original example used ''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.)). 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. ===== Script Execution ===== Run the [[http://localhost:4567/eg-259/examples/lecture5/hello_js_world.html|script]]. ---- Here is the script in full: Our first JavaScript script

Our first JavaScript script

Use this file as a template for your own.

Back to examples

© Swansea University 2013

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. ===== General Syntactic Characteristics ===== * For this module, all JavaScript scripts will be embedded in HTML5 documents * Either directly, as in * Or indirectly, as a file specified in the //src// attribute of '' ===== Playing with JavaScript ===== At least 3 ways: * Put code in ''

Real roots of a quadratic equation

Use this file as a template for your own JavaScript experiments.

Back to examples
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("

The first root is: " + root1 + "
"); result_element.append("The second root is: " + root2 + "

");
===== Summary of this Lecture ===== //Getting started with JavaScript// * [[eg-259:lecture5#overview_of_javascript|Overview of JavaScript]] * [[eg-259:lecture5#object_orientation_and_javascript|Object Orientation and JavaScript]] * [[eg-259:lecture5#general_syntactic_characteristics|General Syntactic Characteristics]] * [[eg-259:lecture5#primitives_operations_and_expressions|Primitives, Operations, and Expressions]] * [[eg-259:lecture5#screen_output_and_keyboard_input|Screen Output and Keyboard Input]] ===== Learning Outcomes (1) ===== **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//: - Describe briefly three major differences between Java and JavaScript. - Describe briefly three major uses of JavaScript on the client side. - Describe briefly the basic process of event-driven computation. - What are the two categories of properties in JavaScript? - Describe the two ways to embed a JavaScript script in an HTML document. ===== Learning Outcomes (2) ===== //At the end of this lecture you should be able to answer these questions//: - What are the advantages and disadvantages of JavaScript? - What are the two forms of JavaScript components? - What are the five primitive data types in JavaScript? - Do single-quoted string literals have any different characteristics than double-quoted string literals? ===== Learning Outcomes (3) ===== //At the end of this lecture you should be able to answer these questions//: - In what circumstances would a variable have the value ''undefined''? - If the value undefined is used as a Boolean expression, is it interpreted as ''true'' or ''false''? - What value does ''typeof'' return for an ''object'' operand? ===== Learning Outcomes (4) ===== //At the end of this lecture you should be able to answer these questions//: - What is the usual end-of-line punctuation for the string operand to ''document.write''? - What is the usual end-of-line punctuation for the string operand to ''alert''? - What is the usual end-of-line punctuation for the string operand to ''console.log''? - Describe the operation of the ''prompt'' method. There are many more review questions [[eg-259:review:javascript01|available]]. ===== Further Reading ===== The [[http://eloquentjavascript.net/chapter1.html|Introduction]] and the opening of [[http://eloquentjavascript.net/chapter2.html|Chapter 1]] of Eloquent JavaScript cover much the same material as these notes and include some interactive exercises that you can try. ===== Exercise ===== 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. - Modify the roots programme so that it deals properly with numbers and uses ''console.log'' for output. - //Input//: Three numbers, using prompt to get each. //Output//: The largest of the three input numbers. //Hint//: Use the predefined function ''Math.max''. ===== What's Next? ===== Programming in JavaScript * [[eg-259:lecture6#learning_outcomes_control_statements|Control Statements]] * [[eg-259:lecture6#learning_outcomes_objects|Objects]] * [[eg-259:lecture6#learning_outcomes_arrays|Arrays]] * [[eg-259:lecture6#learning_outcomes_functions|Functions]] * [[eg-259:lecture6#constructors|Constructors]] [[eg-259:case-studies:1|Previous Lecture]] | [[eg-259:home]] | [[eg-259:lecture6|Next Lecture]]