1 / 117

JavaScript

JavaScript. Source from multiple external sources from the Internet over the years Please PM me to claim credit if needed Known Arthur: John Mitchell (2008), Tom Horton, Alfred C Weaver, Richard Sinn. JavaScript History. Developed by Brendan Eich at Netscape

graham
Download Presentation

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JavaScript Source from multiple external sources from the Internet over the years Please PM me to claim credit if needed Known Arthur: John Mitchell (2008), Tom Horton, Alfred C Weaver, Richard Sinn

  2. JavaScript History • Developed by Brendan Eich at Netscape • Scripting language for Navigator 2 • Later standardized for browser compatibility • ECMAScript Edition 3 (aka JavaScript 1.5) • Related to Java in name only • Name was part of a marketing deal • Various implementations available • Spidermonkey interactive shell interface • Rhino: http://www.mozilla.org/rhino/

  3. HTML Background • Many “markup” languages in the past • SGML: Standard Generalized Markup Language • HTML (Hypertext Markup Language) based on SGML • XML (eXtensible Markup Language) “replaces” SGML • XHTML is replacing HTML

  4. Principles • Distinguish structure from presentation • Presentation based on structure • Presentation may vary, perhaps based on display characteristics, user-preference, etc. • People like to ignore this idea • E.g. use <B> vs. <EM> • <font> tag? • XML and CSS or XSL

  5. Tags and Elements • Example of an element: <name attr1=“attrval”>content</name> • Begin and end tags set off a section of a document • Has a semantic property by tag-name • Modified by attributes • “content” can contain other elements • Elements nest, don’t “overlap” • Empty-elements: no end tag • <br /> <img … /> • Note space before />

  6. Basic HTML Structure • Comments:<!-- … --> • Example: <html> <head> … </head> <body> …. </body> </html> <--- title, meta-tags, etc. (not displayed) <--- main content (displayed)

  7. Larger Example <html> <head> <title>An Example</title> </head> <body> <h3><hr>An Example</h3> <p align="left"> <font face="Comic Sans MS" size="4"><b> Hello World!</b></font> </p> <p align="right"> <font size="5"><u>I am 21.</u></font> </p> <!-- see next column --> <p> <ol type="I" start=7> <li><font color=#00FF00>Green</font></li> <li>Yellow</li> <ul type=square> <li>John</li> <li>Mike</li> </ul> </ol> </p> </body> </html>

  8. Displays As…

  9. Basic Tags • Text display: • <em>, <strong>, <em> • Structure: • <h1>, <h2>, <h3> • <p> • <ul>, <ol>, <blockquote> • Attributes: • Align, text, bgcolor, etc.

  10. Basic Tags (2) • Links: <a href=“…”>…</a> • Images: • <img src=“…”> an empty tag • Tables • Use an editor! • Forms: later

  11. More HTML • Learn on your own • You may never code in “raw” HTML • You may need to tweak HTML files created by a tool • You will need to understand HTML to code in JavaScript etc. • You will need to understand HTML to know limitations on how docs on the web can be structured

  12. Document Object Model (DOM) • An model for describing HTML documents (and XML documents) • A standard (ok, standards) • Independent of browser, language • (ok, mostly) • A common set of properties/methods to access everything in a web document • APIs in JavaScript, for Java, etc.

  13. DOM • You getanything youwant from… • More info: http://en.wikipedia.org/wiki/Document_Object_Model

  14. JavaScript Statements <html> <head><title>My Page</title></head> <body> <script language="JavaScript"> document.write('This is my first  JavaScript Page'); </script> </body> </html> Note the symbol for line continuation

  15. HTML written inside JavaScript JavaScript Statements <html> <head><title>My Page</title></head> <body> <script language=“JavaScript"> document.write('<h1>This is my first  JavaScript Page</h1>'); </script> </body> </html>

  16. JavaScript Statements <html> <head><title>My Page</title></head> <body> <p> <a href="myfile.html">My Page</a> <br /> <a href="myfile.html" onMouseover="window.alert('Hello');"> My Page</A> </p> </body> </html> JavaScript written inside HTML An Event

  17. Example Statements <script language="JavaScript"> window.prompt('Enter your name:',''); </script> <form> <input type="button" Value="Press" onClick="window.alert('Hello');"> </form> Another event Note quotes: " and '

  18. HTML Forms and JavaScript • JavaScript is very good at processing user input in the web browser • HTML <form> elements receive input • Forms and form elements have unique names • Each unique element can be identified • Uses JavaScript Document Object Model (DOM)

  19. Naming Form Elements in HTML <form name="addressform"> Name: <input name="yourname"><br /> Phone: <input name="phone"><br /> Email: <input name="email"><br /> </form>

  20. Forms and JavaScript document.formname.elementname.value Thus: document.addressform.yourname.value document.addressform.phone.value document.addressform.email.value

  21. Using Form Data Personalising an alert box <form name="alertform"> Enter your name: <input type="text" name="yourname"> <input type="button" value= "Go" onClick="window.alert('Hello ' + document.alertform.yourname.value);"> </form>

  22. Tips • Check your statements are on one line • Check your " and ' quotes match • Take care with capitalisation • Lay it out neatly - use tabs • Remember  in the workbook denotes a continuing line • Be patient Presentation slides adapted from scom.hud.ac.uk/scomsjw/Web%20Authoring%20Module/Lecture%20Slides/introjs.ppt

  23. W3C Standards • XML, XHTML • CSS, XSL • XSLT • DOM • ECMAScript • etc

  24. JavaScript • An example of a “scripting” langauge that is embedded in HTML documents • The browser’s display engine must distinguish from HTML and Script statements • Others like this: • PHP (later in the course)

  25. History • JavaScript created by Netscape • JScript created by Microsoft • IE and Netscape renderings are slightly different • Standardized by European Computer Manufacturers Association (ECMA) • http://www.ecma-international. org/publications /standards/Ecma-262.htm

  26. General Format • <!doctype ...> • <html> • <Head> • <Title> Name of web page </title> • <script type="text/javascript"> • ...script goes here • </script> • </head • <body> • ...page body here: text, forms, tables • ...more JavaScript if needed • ...onload, onclick, etc. commands here • </body> • </html>

  27. Characteristics • Case sensitive • Object oriented • Produces an HTML document • Dynamically typed • Standard operator precedence • Overloaded operators • Reserved words

  28. Characteristics • Division with / is not integer division • Modulus (%) is not an integer operator • 5 / 2 yields 2.5 • 5.1 / 2.1 yields 2.4285714285714284 • 5 % 2 yields 1 • 5.1 % 2.1 yields 0.8999999999999995

  29. Characteristics • " and ' can be used in pairs • Scope rules for variables • Strings are very common data types • Rich set of methods available • Arrays have dynamic length • Array elements have dynamic type • Arrays are passed by reference • Array elements are passed by value

  30. Motivation for JavaScript • Netscape, 1995 • Netscape > 90% browser market share • Opportunity to do “HTML scripting language” • Brendan Eich I hacked the JS prototype in ~1 week in May And it showed! Mistakes were frozen early Rest of year spent embedding in browser • Common uses of JavaScript include: • Form validation • Page embellishments and special effects • Dynamic content manipulation • Emerging Web 2.0: client functionality implemented at client • - ICFP talk, 2006

  31. Example 1: simple calculation <html> … <p> … </p> <script> var num1, num2, sum num1 = prompt("Enter first number") num2 = prompt("Enter second number") sum = parseInt(num1) + parseInt(num2) alert("Sum = " + sum) </script> … </html>

  32. Example 2: browser events Mouse event causes page-defined function to be called <script type="text/JavaScript"> function whichButton(event) { if (event.button==1) { alert("You clicked the left mouse button!") } else { alert("You clicked the right mouse button!") }} </script> … <body onmousedown="whichButton(event)"> … </body> Other events: onLoad, onMouseMove, onKeyPress, onUnLoad

  33. Example 3: page manipulation • Some possibilities • createElement(elementName) • createTextNode(text) • appendChild(newChild) • removeChild(node) • Example: Add a new list item: var list = document.getElementById(‘list1') var newitem = document.createElement('li') var newtext = document.createTextNode(text) list.appendChild(newitem) newitem.appendChild(newtext) This example uses the browser Document Object Model (DOM). For now, we will focus on JavaScript as a language, not its use in the browser.

  34. Design goals • Brendan Eich’s 2006 ICFP talk • Make it easy to copy/paste snippets of code • Tolerate “minor” errors (missing semicolons) • Simplified onclick, onmousedown, etc., event handling, inspired by HyperCard • Pick a few hard-working, powerful primitives • First class functions for procedural abstraction • Objects everywhere, prototype-based • Leave all else out!

  35. Language basics • JavaScript is case sensitive • HTML is not case sensitive; onClick, ONCLICK, … are HTML • Statements terminated by returns or semi-colons (;) • x = x+1; same as x = x+1 • Semi-colons can be a good idea, to reduce errors • “Blocks” • Group statements using { … } • Not a separate scope, unlike other languages (see later slide) • Variables • Define a variable using the var statement • Define implicitly by its first use, which must be an assignment • Implicit definition has global scope, even if it occurs in nested scope?

  36. Tutorial Objectives • Understand basic JavaScript syntax • Create an embedded and external script • Work with variables and data • Work with data objects and extract values from dates • Work with expressions and operators • Create and call a JavaScript function • Work with arrays and conditional statements • Learn about program loops

  37. Server-Side Programs • a user must be connected to the Web server to run the server-side script • only the programmer can create or alter the script • the system administrator has to be concerned about users continually accessing the server and potentially overloading the system

  38. Client-Side Programs • solve many of the problems associated with server-side scripts • can be tested locally without first uploading it to a Web server • are likely to be more responsive to the user • can never completely replace server-side scripts

  39. Introduction to JavaScript • JavaScript is an interpreted programming or script language from Netscape. • JavaScript is used in Web site development to such things as: • automatically change a formatted date on a Web page • cause a linked-to-page to appear in a popup window • cause text or a graphic image to change during a mouse rollover

  40. Requires the JDK to create the applet Requires a Java virtual machine to run the applet Applet files are distinct from the XHTML code Source code is hidden from the user Programs must be saved as separate files and compiled before they can be run Programs run on the server side Requires a text editor Required a browser that can interpret JavaScript code JavaScript can be placed within HTML and XHTML Source code is made accessible to the user Programs cannot write content to the hard disk Programs run on the client side Java vs. JavaScript

  41. ECMAScript • The responsibility for the development of a scripting standard has been transferred to an international body called the European Computer Manufacturers Association (ECMA). • The standard developed by the ECMA is called ECMAScript, though browsers still refer to it as JavaScript. • The latest version is ECMA-262, which is supported by the major browsers.

  42. Other Client-side Languages • Internet Explorer supports JScript. • JScript is identical to JavaScript, but there are some JavaScript commands not supported in JScript, and vice versa. • Other client-side programming languages are also available to Web page designers, such as the Internet Explorer scripting language, VBScript.

  43. Example of Web Site using JavaScript

  44. Writing a JavaScript Program • The Web browser runs a JavaScript program when the Web page is first loaded, or in response to an event. • JavaScript programs can either be placed directly into the HTML file or they can be saved in external files. • placing a program in an external file allows you to hide the program code from the user • source code placed directly in the HTML file can be viewed by anyone

  45. Writing a JavaScript Program • A JavaScript program can be placed anywhere within the HTML file. • Many programmers favor placing their programs between <head> tags in order to separate the programming code from the Web page content and layout. • Some programmers prefer placing programs within the body of the Web page at the location where the program output is generated and displayed.

  46. Using the <script> Tag • To embed a client-side script in a Web page, use the element:<script type=“text/javascript” >script commands and comments</script> • To access an external script, use:<script src=“url” type=“text/javascript”>script commands and comments</script>

  47. Comments • The syntax for a single-line comment is:// comment text • The syntax of a multi-line comment is:/* comment text covering several lines*/

  48. Hiding Script from Older Browsers • You can hide the script from these browsers using comment tags: <script type=“text/javascript”> <!-- Hide from non-JavaScript browsers JavaScript commands // Stop hiding from older browsers --> </script> • When a Web browser that doesn’t support scripts encounters this code, it ignores the <script> tag.

  49. Writing Output to a Web Page • JavaScript provides two methods to write text to a Web page: • document.write(“text”); • document.writeln(“text”); • The document.writeln() method differs from document.write() in that it attaches a carriage return to the end of each text string sent to the Web page. document.write("<h3>News Flash!</h3><br />");

More Related