Javascript tutorial - basics

From EduTech Wiki
Jump to: navigation, search

1 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
  • Some sections need to be expanded a bit
  • These tutorials were developed for XHTML 1.0. Code should still work for HTML5 but could be adapted (mainly simplified) for HTML5.

2 Reminder: HTML, XHTML and CSS

2.1 HTML

A simple HTML 4 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

  • XHTML is an XML application (i.e. it uses the XML formalism).
  • XHTML 1 is more powerful than HTML 4, 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 !

XHTML 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

As of 2014, HTML5 did become the most popular HTML variant for new developments. XHTML is out of favor. The structure of an HTML5 page is slightly simpler:

<!doctype html>
<html>
  <head>
      <title>My first HTML 5 document</title>
      <meta charset="UTF-8">
  </head>
  <body>
      <p>Hello world!</p>
  </body>
</html>

2.2 CSS principles

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";
      }

2.3 Using JavaScript

Finally, lets see how we can embed JavaScript (JS) code in an HTML page using the script</script> tag. There are two methods, put JS code inside a page and import JS code from a file.

Using JS code inside HTML

<script type="text/javascript">
// Below some JavaScript code
var message = "Hello reader";
</script>

More complex code is usually defined in external files and linked like this:

 <script type="text/javascript" src="external_file.js"></script>

The <code>source element can be used both within the head and the body section.

3 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 !)

3.1 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.

3.2 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
  • 2008: JavaScript 1.8 - Firefox 3.0

Fore more information, you may consult Wikipedia, e.g. start from ECMAScript and then read JavaScript. There are many JS articles on Wikipedia. Some are good.

3.3 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
  • ....

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

3.4 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")

Else, you can type in JS code, by opening the developer Interface: Hit F12.

For debugging always open the error console !!!!

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

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

4 JavaScript programming bare bones

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

4.1 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

4.2 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?"))

Files: 1-4-prompt-confirm.html and 1-4-prompt-confirm.js. Note: code shown uses programming concepts that will be explained below.

4.3 Variables

Variables can be use to store any kind of data, e.g. numbers or text. That kind of data is also called values and there exist different kinds of datatypes. For the moment, just keep in mind the following examples.

Remembering a number
var age = 36;
Remembering a string
var name = "Dorothy";

The result of prompting in the previous example is stored in a variable for later reuse. Variables are just containers that can hold data from any source

Rembembering the output of a method
var result = sophisticated_routine ("complex data");

Below we show how to remember what a person answered to a prompt (this will not work with IE7(7/8) unless you reconfigure your browser).

 var answer = prompt("Please, could you tell me a secret ?","");

File: 1-4-prompt-confirm.html

It is possible to assign new (and different) values to a variable while the program runs.

var age = 37;

This is exactly why variables are called variables ...

4.4 Functions

  • Functions are little programs that can be reused (like recipes)
  • The difference between functions and recipes is that functions can be given information, i.e. so-called arguments to deal with.
  • Functions can be called, i.e. executed.

Below is the syntax for a simple function that is not given any information to deal with (no arguments):

 function name () {
   // instructions (this is a comment and does not do anything).
 }

The following function when called will simply execute the line alert(....);

 function popupMessage() {
   alert("Hello, world!");
 }

To call this function you would have to write a line of code like this:

 popupMessage();

Now let's look at an example that will use an argument:

 function popupMessage_2(cool_message) {
   alert(cool_message);
 }

 popupMessage_2("Hello, beautiful world!");

4.5 Objects

In JavaScript, there are two kinds of objects. So-called built-in objects that are part of the DOM and objects you may create yourself.

Example of a built-in object

window is a system variable pointing to 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

Example of a custom object
var obj       = new Object();
obj.name      = "EduTech Wiki";
obj.size      = "> 1000 articles";
var site_name = obj.name;

Equivalent code using an other syntax that would be practical for real-time changes.

var obj       = {}; // syntaxe littérale
obj."name     = "EduTech Wiki";
obj."size"    = "> 1000 articles";
var site_name = obj.["name"];

Equivalent compact code.

var obj = {
   name: "EdutechWiki",
   size: "> 1000 articles"
   }
var site_name = obj.name;

Equivalent code using a constructor function. In the code below, "web_site" is a class, simply defined as function.

function web_site (name, size) {
   this.name = name;
   this.size = size;
   }
// The new statement will create an instance of a class
var obj = new web_site("EduTechWiki","> 1000 articles");
var site_name = obj.name;

4.6 DOM

DOM, i.e. Document Object Model refers to the name of the data structure of an HTML/XML page and the associated retrieval and modification methods

Let's illustrate a little bit of DOM programming now. To change the content of an HTML element, give it first a unique id in the HTML file (pText is an ID):

  <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

4.7 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
  • Write triggers that 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
<script type="text/javascript">
// Below some JavaScript code
var name = "DKS";
window.onload=init;
// The "hitme" button to trigger the ''start'' function when pressed
function init() {
      document.getElementById("hitme").onclick = start;
      }
</script>
  • 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.

Below, we will show some examples, do not worry if you do not (yet) understand details

4.8 Note on JavaScript and true XHTML

Valid XHTML served as 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.

4.9 User interface widgets

To trigger JavaScript functions one may write event handlers for many kinds of user actions. Often, JavaScript calls are executed when the page loads

The most simple way to call a JavaScript function is to use HTML forms

5 Examples

Below we introduce some examples that would need some extra explantions. Some "old" style techniques will not work in IE7 or IE8, which is not an issue since "old style" DOM was never really standardized. There exist Microsoft specific "old-style" techniques which we will not show here.

5.1 simple popups and buttons

5.1.1 A popup/DOM/onload example

The following example shows how to trigger a JavaScript function when the page loads into the browser. Syntax:

 window.onload = function_name;

In this code we do not call the function, but we give JavaScript the function name that should be called when the page loads. For newbie programmers: This is why the parenthesis are missing after function_name.

 <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>

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

A popup/DOM/onload example

Remember:

  • function definitions belong in the head
  • You may trigger a function at page load (like above)

5.1.2 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. With this method we assign a functionall to the HTML onload attribute.

File: 1-6-dom-change.html

popup/DOM/onload example - old style
 <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>

5.1.3 A popup/DOM/button example - new style

This example show how to create a button that the user can press with the HTML forms element.

   <form>
    <input id="hitme" type="button" value="Press me"/>
   </form>

This HTML code says:

  • Let's define a button <input type=button" ...
  • It's label will be "Press me"
  • It's ID is "hitme".

We then can in the JavaScript code tell the button what function to call when it is pressed.

<!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>

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

A popup/DOM/button example - new style

5.1.4 A popup/DOM/button example - old style

Below is old DOM 0 style that assigns a function call to the onclick attribute - 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>
popup/DOM/button example - old style

5.2 Quizzes with radio buttons

See HTML forms tutorial

6 Acknowledgement

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

7 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/)