Javascript tutorial - basics: Difference between revisions

The educational technology and digital learning wiki
Jump to navigation Jump to search
mNo edit summary
mNo edit summary
Line 174: Line 174:
  document.write("Hello, COAP 2130!");
  document.write("Hello, COAP 2130!");
</source>
</source>
File: [[http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/1-1-hello.html 1-1-hello.html]]
File: [http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/1-1-hello.html 1-1-hello.html]


The following code will create a popup window with a little message
The following code will create a popup window with a little message
Line 180: Line 180:
  alert("Hello, world!");
  alert("Hello, world!");
</source>
</source>
File: [[http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/1-3-alert.html 1-3-alert.html]]
File: [http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/1-3-alert.html 1-3-alert.html]


Tip: Try this out in the Firefox error console or with a javascript URL in IE
Tip: Try this out in the Firefox error console or with a javascript URL in IE
Line 192: Line 192:
</source>
</source>


File: [[http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/1-4-prompt-confirm.html 1-4-prompt-confirm.html]]
File: [http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/1-4-prompt-confirm.html 1-4-prompt-confirm.html]


'''Variables''':
'''Variables''':
Line 201: Line 201:
  var answer = prompt("Please, could you tell me a secret ?","");
  var answer = prompt("Please, could you tell me a secret ?","");
</source>
</source>
File: [[http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/1-4-prompt-confirm.html 1-4-prompt-confirm.html]]
File: [http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/1-4-prompt-confirm.html 1-4-prompt-confirm.html]


'''Functions''':
'''Functions''':
Line 234: Line 234:
</source>
</source>


File: [[http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/1-2-external-code.html 1-2-external-code.html]]
File: [http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/1-2-external-code.html 1-2-external-code.html]


'''DOM'''
'''DOM'''
Line 273: Line 273:
</source>
</source>


File: [[http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/1-4-prompt-confirm.html 1-4-prompt-confirm.html]]
File: [http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/1-4-prompt-confirm.html 1-4-prompt-confirm.html]


=== JavaScript and HTML ===
=== JavaScript and HTML ===
Line 310: Line 310:
* '''A popup/DOM/onload example '''
* '''A popup/DOM/onload example '''


File: [[http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/1-6-dom-change-modern.html 1-6-dom-change-modern.html ]]
File: [http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/1-6-dom-change-modern.html 1-6-dom-change-modern.html]


<source lang="xml">
<source lang="xml">
Line 345: Line 345:
Most often you will rather find old DOM 0, not as good since HTML is mixed with JS.
Most often you will rather find old DOM 0, not as good since HTML is mixed with JS.


File: [[http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/1-6-dom-change.html  1-6-dom-change.html ]]
File: [http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/1-6-dom-change.html  1-6-dom-change.html]


[[image:js-intro-5.png|frame|none| <LABEL> ]]
[[image:js-intro-5.png|frame|none| <LABEL> ]]
Line 373: Line 373:
* '''A popup/DOM/button example - new style'''
* '''A popup/DOM/button example - new style'''


File: [[http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/week-1-2/1-7-dom-change-button-modern.html 1-7-dom-change-button-modern.html]]
File: [http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/week-1-2/1-7-dom-change-button-modern.html 1-7-dom-change-button-modern.html]


<source lang="xml">
<source lang="xml">

Revision as of 22:56, 27 September 2009

This article or section is currently under construction

In principle, someone is working on it and there should be a better version in a not so distant future.
If you want to modify this page, please discuss it with the person working on it (see the "history")

Introduction

Learning goals
  • Learn about JavaScript's puposes
  • Be able to reuse and modify some simple JavaScript functions
  • Be able to reuse JavaScript libraries
Prerequisites
Concurrent
Moving on
  • ...
Level and target population
  • Beginners
Remarks

Reminder: HTML, XHTML and CSS

A simple HTML page may look like this

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 <html>
   <head>
    <title>Simple HTML Page</title>
     <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
   </head>
   <body>
     <h1>Simple HTML Page</h1>
     <p>Hello</p>
     <hr>
   </body>
 </html>
Important elements of an HTML page

Notes: Navigators are very forgiving, you may omit the doctype, the encoding declarations, or even the head. But your page will not validate (not acceptable in most professional settings).

An XHTML Page looks slightly different

  • All most recent HTML versions are XHTML (2009), although HTML 5 will be "HTML again"
  • XHTML is an XML application (i.e. it uses the XML formalism).
  • XHTML is more powerful than HTML, but simpler, stricter and somewhat less forgiving ....
  • All tags are lower case, all tags must be closed (think “boxes” within “boxes”) !!!
  • <html> must include xmlns, i.e. a namespace declaration
  • The XML declaration on top is not absolutely mandatory, but the DOCTYPE is !

Here is code for an example page

 <?xml version = "1.0" encoding="UTF-8"?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 <html xmlns = "http://www.w3.org/1999/xhtml">
  <head>
    <title>Object Model</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  </head>
  <body>
    <h1>Welcome to our Web page!</h1>
    <p>Enjoy ! </p>
  </body>
 </html>

File: preq-xhtml-page.html

Anatomy of an XHTML page

Now, let's recall some principles from CSS:

  • CSS Style sheet = set of rules that describe how to render XML or (X)HTML elements

Each rule has two parts:

  • The selector: defines to which elements a rule applies
  • The declaration: defines rendering, i.e. defines values for style properties
Anatomy of CSS rules

A simple example for HTML tags

 H1 { color: red }
 P  { font-face: Verdana, sans-serif ; font-size: 12pt}
 H1, H2, H3 { color : blue }
 H1.ChapterTOC, H2.PeriodeTOC, H2.ExerciceTOC, H2.SectionTOC  {
         display: block;text-indent: 30pt;    
         text-align: left; font-size: 14.000000pt;
         font-weight: Bold;     font-family: "Times";
      }

History and purpose of JavaScript ?

JavaScript was originally developed by Netscape (under the name LiveScript). Microsoft adopted it under the name JScript. The name “JavaScript” reflects certain syntactic similarities with JAVA (but JavaScript and Java are very different !)

Uses

The main uses of JavaScript are the following:

Interactive web pages

  • Interactive forms
  • Interactive applications with HTML forms (par ex. tests or quizzes)
  • Verification of HTML forms before sending them off for “server-side” treatment

Interactive pages (DHTML)

  • Richer HTML pages (ex. “highlighting”, menus, etc.)
  • Applications that look like desktop applications (e.g. Google applications)
  • Animations
  • Often, these pages can directly communicate with a server (known as AJAX).

User-centered contents

  • Generation of HTML pages according to user profile
  • Plugin detection, etc.

Versions of JavaScript

JavaScript has a long and complicated history:

  • 1994: Mocha, then Live script - Netscape 1.x
  • December 1995: renamed to JavaScript - Netscape 2.0
  • August 1996: JScript - Internet Explorer 3.0
  • June 1997: First edition of ECMA-262
  • .....
  • Nov 2006: JScript 5.7 - IE 7.0 based on ECMA-262 3rd ed.
  • 2007: JavaScript 1.7 - Firefox 2.0

Fore more information, you may consult Wikipedia, e.g. start from:

Other uses of ECMA/Java/J-Script

  • ActionScript 3 was based on a recent (but killed) ECMA standard proposition
  • Server-side scripting in .NET
  • Client-side scripting for other formats (SVG, VRML, X3D, PDF, etc.)
  • Some dashboard widgets (MacOS X, Yahoo, ...)
  • Some desktop programs (e.g. the user interface of Firefox or Adobe CS3) can be scripted with some JS-like language
  • ....

Tools

To code Javascript, you should use a programming editor (and not Word!). If you can, try to find an editor that does syntax highlighting and indentation, e.g. Notepad++

To test small bits of code in Firefox:type the URL: "JavaScript:" or use the menu: Tools->Error Console. This will open the error console, you then can enter JS code in the small input window on top:

alert("hi there")

To test small bits of code in IE, use the "javascript:" protocol identifier followed by code, e.g:

javascript:alert("hi there")

For debugging always open the error console !!!!

  • in Firefox, see above
  • in IE: Tools->Internet Options ->Advanced (tick something like "Display notifications .." under the navigation header) ... sorry I don’t have an English Windows version at hand.

Firefox users also should install several Add-ons like "DomInspector", "WebDevelopper", "GreaseMonkey, .... See browser extensions.

JavaScript programming bare bones

Donc panic, the idea is to give you a rough picture of what happens in the examples.

Built-in methods

The following line of code tells the browser window to write out some text

 document.write("Hello, COAP 2130!");

File: 1-1-hello.html

The following code will create a popup window with a little message

 alert("Hello, world!");

File: 1-3-alert.html

Tip: Try this out in the Firefox error console or with a javascript URL in IE

Prompting and confirming

The following code will prompt the user in various ways. The prompt () message will

 prompt("Please, could you tell me a secret ?","");
 confirm("Are you sure that you really wanted to give your secret away?"))

File: 1-4-prompt-confirm.html

Variables:

  • Result of prompting is stored in a variable for later reuse
 var answer = prompt("Please, could you tell me a secret ?","");

File: 1-4-prompt-confirm.html

Functions:

  • Functions are little programs that can be reused (like recipes)
  • Syntax for a simple function that is not given any information to deal with (no arguments):
 function name () {
   // instructions
 }
  • Example: This function when called will simply execute the line alert(....);
 function popupMessage() {
   alert("Hello, world!");
 }

Objects:

window is an object that represents the navigator’s display area, you can tell it to execute a function when it loads a page (assign its event handler onload property a function name)

 window.onload = writeMessage;

 function writeMessage() {
     document.getElementById("helloMessage").innerHTML = "Hello, world!";
 }

File: 1-2-external-code.html

DOM

  • To change content of an HTML element, give it first a unique id, i.e. the HTML file:
  <p id = "pText">Welcome to our Web page!</p>
  • Then, in JavaScript, you can program somthing like:
 var p = document.getElementById("pText");
 p.innerHTML = "Heh I changed your text";

or in a single line:

 document.getElementById("pText").innerHTML = "Heh I changed your text";

see the previous example

Conditionals

  • If this is true do this, else do that ....
 var answer = prompt("Please, could you tell me a secret ?","");

 if (answer) {
     alert("You told me: " + answer);
   }
 else {
     alert("You refused to answer");
   }

File: 1-4-prompt-confirm.html

JavaScript and HTML

Programming in JavaScript usually means two things:

  • Define functions, i.e. executable recipes that do something like ask questions from the user, popup information windows, compute an animation
  • Trigger (call) these functions after some user action. E.g. user loads the page, user moves the mouse, user clicks on a button ....

Usually, according to this logic, you put JavaScript code in two locations:

  • JavaScript functions are defined in the <head> .. </head> and within "script" tags
  • More complex code is usually defined in external files and linked like this:
 <script type="text/javascript" '''src="external.js"'''></script>
  • The principle: Definitions of functions and variables etc. belong in the head within the script tag or in some external file (loaded also through the script tag).
  • JavaScript functions can be called or triggered in various ways from the body of the HTML document, e.g.:
  • JavaScript instructions can be inserted within "script" tags (as in the head)
  • JavaScript functions can be triggered by "HTML inline" event handler definitions (old style)
  • Event handling also may be defined purely within JS code (new DOM style) by assigning function names to event handling properties (new style).

... don't panic here. we will see the operational details later.


In the next four slides we will show some examples, do not worry if you do not (yet) understand details

All examples can be found here: http://tecfa.unige.ch/guides/js/ex/coap/week-1-2/

  • A popup/DOM/onload example

File: 1-6-dom-change-modern.html

 <html xmlns = "http://www.w3.org/1999/xhtml">
    <head>
       <title>Object Model</title>
       '''<script type = "text/javascript">'''
          window.onload = start;

          '''function''' '''start(){'''
             var p = document.getElementById("pText");
             alert( "Page contents : " + p.innerHTML );
             p.innerHTML = "Thanks for coming.";
             alert( "Page contents changed to : " + p.innerHTML );
             p.innerHTML = "Cool, isn't it ?";
          '''}'''
       '''</script>'''
    </head>

    <body>
       <p id = "pText">Welcome to our Web page!</p>
    </body>
<LABEL>

Remember:

  • function definitions belong in the head
  • You may trigger a function at page load (like above)
  • A popup/DOM/onload example - old style

Most often you will rather find old DOM 0, not as good since HTML is mixed with JS.

File: 1-6-dom-change.html

<LABEL>
 <html xmlns = "http://www.w3.org/1999/xhtml">
    <head>
       <title>Object Model</title>
       '''<script type = "text/javascript">'''
          '''function''' '''start()''' 
          '''{'''
             var p = document.getElementById('''"pText"''');
             alert( "Page contents : " + p.innerHTML );
             p.innerHTML = "Thanks for coming.";
             alert( "Page contents changed to : " + p.innerHTML );
             p.innerHTML = "Cool, isn't it ?";
          '''}'''
       '''</script>'''
    </head>

    <body '''onload = "start()"'''>
       <p id = '''"pText"'''>Welcome to our Web page!</p>
    </body>
 </html>
  • A popup/DOM/button example - new style

File: 1-7-dom-change-button-modern.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Simple DOM/innerHTML demo</title>
    <script type = "text/javascript">
      window.onload=init;

      function init() {
      // This will tell the "hitme" button to trigger a start function
      // when pressed
      document.getElementById("hitme").onclick = start;
      }

      function start() {
      var p = document.getElementById("pText");
      alert( "Page contents : " + p.innerHTML );
      p.innerHTML = "Thanks for coming.";
      alert( "Page contents temporarly changed to : " + p.innerHTML );
      p.innerHTML = "Cool, isn't it ?";
      }
    </script>
  </head>
  <body>
    <p id = "pText">Welcome to our Web page!</p>

    <hr/>
   <form>
    <input id="hitme" type="button" value="Press me"/>
   </form>
  </body>
</html>
<LABEL>
  • A popup/DOM/button example - old style
  • This is old DOM 0 style - does not work with IE 7

File: 1-7-dom-change-button.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Simple DOM/innerHTML demo</title>
    <script type = "text/javascript">
      function start() {
      var p = document.getElementById("pText");
      alert( "Page contents : " + p.innerHTML );
      p.innerHTML = "Thanks for coming.";
      alert( "Page contents temporarly changed to : " + p.innerHTML );
      p.innerHTML = "Cool, isn't it ?";
      }
    </script>
  </head>
  <body>
    <p id = "pText">Welcome to our Web page!</p>

    <hr/>
    <!-- When the user clicks the button, the JS "start()" function will be called -->
    <form>
     <input onclick="start();" type="button" value="Press me"/>
    </form>
  </body>
</html>
<LABEL>
  • Standardization etc.

Note on standardization

  • The JavaScript language itself (ECMAScript) is fairly cross-browser compatible
  • Event handling (DOM 2) and DOM 1 (querying and modifying the document) is not fully standard nor fully implemented by all browsers
  • More advanced stuff (parts of DOM 2 and DOM 3) is less frequently implemented

Note on JavaScript and XHTML

  • Valid XHTML requires JavaScript to be inserted within a commented CDATA section
  • Many textbooks do not teach valid XHTML ....
 <script language="javascript">
 // <![CDATA[
    alert ("hello I am alerting you from a valid XHTML Page");
 // ]]>
 </script>
  • An other, better solution is to put the javascript code into an external file.

Acknowledgement

This tutorial was initially created in slide form and has been prepared with the help of:

References

  • Negrino & Smith (2007). JavaScript and Ajax for the Web, Visual QuickStart Guide, Sixth Edition. (You also can consult the book’s examples on its web site or download a zip file from http://www.javascriptworld.com/)