A Very Short Introduction to JavaScript

A Very Short Introduction to JavaScript

If you need more help to get started with JavaScript, read Mozilla’s detailed but dry JavaScript guide at http://developer.mozilla.org/en/JavaScript/Guide.

How a Web Page Uses JavaScript


The JavaScript starts with the <script> element.

If you want to run some JavaScript right away, put it at the end of the <body> section, just before the final </body> tag.
For ex.,

<body>
<script>
alert("We interrupt this web page with a special JavaScript announcement.");
</script>
</body>
In this case, the single line of code triggers JavaScript’s built-in alert() function.

Using a Function


You should wrap each code “task” in a function—a named unit of code that you can call into action whenever you need it.

The best place to put JavaScript functions is in the section of the page.
<head>
...
<script>
function showMessage() {
alert("We interrupt this web page with a special JavaScript announcement.");
}
</script>
</head>

<body>
<script>
showMessage();
</script>
</body>


Moving the Code to a Script File


You can put all your script code inside a script file.

In your web page, define a script block, but don’t supply any code. Instead, add the src attribute and indicate the script file you want to link to:
<head>
<script src="MessageScripts.js">
</script>
</head>
You can also link to JavaScript functions on another website—just remember that the src attribute in the <script> element needs to point to a full URL instead of just a file name.


Document Object Model (DOM)

The Document Object Model (DOM) is an API for HTML and XML documents. It provides a structural representation of the document, enabling you to modify its content and visual presentation by using a scripting language such as JavaScript.

All of the properties, methods, and events available to the web developer for manipulating and creating web pages are organized into objects. Those objects are accessible via scripting languages in most recent web browsers. The DOM is most often used in conjunction with JavaScript. The most important browsers correctly implement the DOM standards defined by the World Wide Web Consortium(W3C).

The core language of JavaScript is standardized by the ECMA TC39 committee as a language named ECMAScript. The WebIDL (Interface Definition Language) specification provides the glue between the DOM technologies and ECMAScript for Web APIs.

The Core DOM defines interfaces which abstracts HTML and XML documents as objects and mechanisms to manipulate this abstraction. From the ECMAScript point of view, objects defined in the DOM specification are called "host objects".

HTML is layered above the abstract concepts defined in DOM Core, HTML also defines the meaning of elements. The HTML DOM includes such things as the className property on HTML elements, or APIs such as document.body.

Responding to Events


You need to use JavaScript events, which are notifications that an HTML element sends out when specific things happen.


So if you want to handle an JavaScript event of an element, you need markup it in the HTML element's attribute with:


<element JavaScriptEvent="JavaScriptEventHandler()">

For ex., if you want to handle the onMouseOver event of an <img> element, you need
markup like this:

<img src="sunny.jpg" alt="A sunny day" onmouseover="showMessage()">
To use events effectively, you need to know which events JavaScript supports. In addition, you need to know which events work on which HTML elements.

You can find a complete reference at http://developer.mozilla.org/en/DOM/element.
Event name Description Applies to HTML elements
onClick Triggered when you click an element. Virtually all elements
onMouseOver Triggered when you move your mouse pointer over an element. Virtually all elements
onMouseOut Triggered when you move your mouse
pointer away from an element.
Virtually all elements
onKeyDown Triggered when you press a key. select, input, textares, a, button
onKeyUp Triggered when you release a pressed key. select, input, textares, a, button
onFocus Triggered when a control receives focus.Controls include text boxes, checkboxes, and so on—see page 112 to learn more. select, input, textares, a, button
onBlur Triggered when focus leaves a control. select, input, textares, a, button
onChange Triggered when you change a value in an input control. In a text box, this event doesn’t fire until you move to another control. select, input type="text", textarea
onSelect Triggered when you select a portion of text in an input control. input type="text", textarea
onError Triggered when your browser fails to download an image. img
onLoad Triggered when your browser finishes downloading a new page or finishes loading an object, like an image. img, body
onUnload Triggered when a browser unloads a page. body

A Few Language Essentials


Variables

In JavaScript, every variable is created by declaring it with the var keyword followed by the variable name. For ex.,
var myMessage = "Everybody loves variables";
The let statement declares a block scope local variable,

let x = 1;

if (x === 1) {
  let x = 2;
  console.log(x);
  // expected output: 2
}

console.log(x);
// expected output: 1

Null Values


If a variable's value is null, it indicates that a given object doesn’t exist.

Variable Scope

  • If you create a variable inside a function (called a local variable), that variable exists only while that function is running.
  • If you create a variable outside a function (called a global variable), its value lasts as long as the page is loaded in the browser.

Variable Data Types


In JavaScript, any variable can hold any type of content.

Operations


Conditional Logic


Loops


JavaScript's for loop provides 3 syntax:
  • the same as that in C and Java
  • 
    for (var i = 0; i <; 5; i++) {
      // Will execute 5 times
    }
    
  • for...in
  • 
    const object = {a: 1, b: 2, c: 3};
    
    for (const property in object) {
      console.log(`${property}: ${object[property]}`);
    }
    // expected output:
    // "a: 1"
    // "b: 2"
    // "c: 3"
    
  • for...of
  • creates a loop iterating over iterable objects.
    
    const array1 = ['a', 'b', 'c'];
    
    for (const element of array1)  {
      console.log(element);
    }
    // expected output: "a"
    // expected output: "b"
    // expected output: "c"
    

Objects


An object is a collection of related data(variable) and/or functionality(function) — which are called properties and methods when they are inside objects.
JavaScript objects can be thought of as simple collections of name-value pairs.
The "name" part is a JavaScript string, while the value can be any JavaScript value — including more objects. This allows you to build data structures of arbitrary complexity.
There are two basic ways to create an empty object:
  • 
      var obj = new Object();
    
  • 
      var obj = {};
    
    Object literal syntax can be used to initialize an object in its entirety:
    
    var obj = {
      name: 'Carrot',
      details: {
        color: 'orange',
        size: 12
      }
    };
    
    Attribute access can be chained together:
    
    obj.details.color;      // orange
    obj['details']['size']; // 12
    
An object is made up of multiple members, each of which has a name and a value. Each name/value pair must be separated by a comma, and the name and value in each case are separated by a colon. The syntax always follows this pattern:

const objectName = {
  member1Name: member1Value,
  member2Name: member2Value,
  member3Name: member3Value
};
An object like this is referred to as an object literal — we've literally written out the object contents as we've come to create it.
You accessed the object's properties and methods using dot notation. There is another way to access object properties — using bracket notation, the following 2 statements are equivalent:

person.age
person['age']
The this keyword refers to the current object the code is being written inside.
For each webpage loaded, an instance of Document is created, called document, which represents the entire page's structure, content, and other features :

const myDiv = document.createElement('div');
const myVideo = document.querySelector('video');

String


Methods:
  • indexOf()
  • The indexOf() method returns the position of the first occurrence of a specified value in a string.

Arrays


Arrays in JavaScript are actually a special type of object. The Array object is used to store multiple values in a single variable.

JavaScript arrays are remarkably flexible. Unlike in many other programming languages, you don’t define the number of items you want an array to store in JavaScript. Instead, you simply begin by creating an empty array with square brackets. For ex.,

var colorList = [];

You can place an array item in a specific position:

colorList[3] = "magenta";


JavaScript arrays use zero-based counting: The first item in an array is in slot 0, the second is in slot 1, and so on.

Using a for loop to process an array is a basic technique in JavaScript:

for (var i = 0; i < colorList.length; i++) {
alert("Found color: " + colorList[i]);
}
Array Methods:
  • push()
  • Adds new elements to the end of an array, and returns the new length.
    colorList.push("red");
  • pop()
  • Removes the last element of an array, and returns that element.
  • splice(index, howmany, item1, ....., itemX)
  • adds/removes items to/from an array, and returns the removed item(s).
    
      index specifies at what position to add/remove items.
    

Functions that Receive and Return Data

Interacting with the Page

JavaScript spends most of its time doing one of these tasks:
  • Updating the page.
  • Retrieving data from the server.
  • Sending data to the server.

Manipulating an Element

DOM is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Objects in the DOM tree may be addressed and manipulated by using methods on the objects. To render a document such as an HTML page, most web browsers use an internal model similar to the DOM. The nodes of every document are organized in a tree structure, called the DOM tree, with topmost node named "Document object". When an HTML page is rendered in browsers, the browser downloads the HTML into local memory and automatically parses it to display the page on screen. The easiest way to get a hold of an object is to identify it with a unique name, which you apply through the id attribute. Once you give your element a unique ID, you can easily locate that object in your code and have JavaScript act on it.
JavaScript includes a handy trick for locating an object: the document.getElement-ById() method. Basically, a document is an object that represents your whole HTML document. The getElementById() method scans a page looking for a specific HTML element. After the object for an HTML element with the assigned ID is got from the document.getElement-ById() method, you can perform a series of operations on it without having to look it up more than once. You can do some operations with HTML objects depending on the type of element you’re working with. You need to know what properties JavaScript lets you play with. The common DOM properties you can use with HTML elements:
Property Descriptioon
className Lets you retrieve or set the class attribute.In other words, this property determines what style (if any) this element uses. Of course, you need to define this style in an embedded or linked style sheet, or you’ll end up with the plain-Jane default formatting.
innerHTML Lets you read or change the HTML inside an element. The innerHTML property is insanely useful, but it has two quirks. First, you can use it on all HTML content, including text and tags. When you set innerHTML, you replace all the content inside this element, including any other HTML elements.
parentElement Provides the HTML object for the element that contains this element.
style The style property returns a full-fledged style object, and you need to add another dot (.) and the name of the style attribute you want to change
tagName Provides the name of the HTML element for this object, without the angle brackets.
To learn more about the properties and methods that a specific HTML element supports, check out the reference at http://developer.mozilla.org/en/DOM/element.

Connecting to an Event Dynamically

Except for wiring up a function using an event attribute, it’s also possible to connect an event to a function using JavaScript code:
  • create or get an HTML object
  • attach an event to the object
For ex.,
<script>
// Keep track of whether the picture has been swapped from day to night.
var dayTime = true;

// This function runs when the onClick event happens.
function swapImage(e) {
  var imgObject = document.getElementById("dayImage");
  // Flip from day to night or night to day, and update the picture to match.
  if (dayTime == true) {
    dayTime = false;
    imgObject.src = "cloudy.jpg";
  } else {
    dayTime = true;
    imgObject.src = "sunny.jpg";
}
</script>

<img id="dayImage" src="sunny.jpg" alt="The weather">

<script>
var imgObject = document.getElementById("dayImage");
imgObject.onclick = swapImage;
</script>
Note, when you use code to connect an event, you must put the entire event name in lowercase letters.

Inline Events

Sometimes, you want to define the function code as a inline function in the same place. For ex.,
imgObject.onclick = function(e) {
...
}

browser developer tools

Every modern web browser includes a powerful suite of developer tools. The devtools live inside your browser in a subwindow that looks roughly like this, depending on what browser you are using. For Chrome: More tools ➤ Developer tools. The developer tools usually open by default to the inspector, which looks something like the following screenshot. You can right-click (Ctrl-click) an HTML element in the inspector and look at the context menu. The JavaScript debugger allows you to watch the value of variables and set breakpoints, places in your code that you want to pause execution and identify the problems that prevent your code from executing properly. For Chrome: Open the Developer tools and then select the Sources tab. There are three panes in the JavaScript Debugger:
  • File list
  • The first pane on the left contains the list of files associated with the page you are debugging. Select the file you want to work with from this list. Click on a file to select it and view its contents in the center pane of the Debugger.
  • Source code
  • Set breakpoints where you want to pause execution.
  • Watch expressions and breakpoints
  • The right-hand pane shows a list of the watch expressions you have added and breakpoints you have set.
    • Watch
    • shows that the listItems variable has been added.
    • Call stack
    • shows you what code was executed to get to the current line.
    • Scopes
    • shows what values are visible from various points within your code.

The JavaScript console

It allows you to run lines of JavaScript against the page currently loaded in the browser, and reports the errors encountered as the browser tries to execute your code. For Chrome: On other browser, open the developer tools and then click the Console tab. To see what happens, try entering the following snippets of code into the console one by one (and then pressing Enter):

alert('hello!');
document.querySelector('html').style.backgroundColor = 'purple';
Let's update the JavaScript object in our file to look like this:

    
After saving and refreshing, try entering some of the following into the JavaScript console on your browser devtools:

person.name
person.bio()
person.greeting()

Working with JSON

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. JSON exists as a string — useful when you want to transmit data across a network. JavaScript provides a global JSON object that has methods available for converting between the native JavaScript object and the string. A JSON object can be stored in its own file, which is basically just a text file with an extension of .json, and a MIME type of application/json.

JSONLint is a validator and reformatter for JSON, a lightweight data-interchange format. Copy and paste, directly type, or input a URL in the editor above and let JSONLint tidy and validate your messy JSON code.

JSON structure

A JSON is a string whose format very much resembles JavaScript object literal format.

{
  "squadName": "Super hero squad",
  "homeTown": "Metro City",
  "formed": 2016,
  "secretBase": "Super tower",
  "active": true,
  "members": [
    {
      "name": "Molecule Man",
      "age": 29,
      "secretIdentity": "Dan Jukes",
      "powers": [
        "Radiation resistance",
        "Turning tiny",
        "Radiation blast"
      ]
    },
    {
      "name": "Madame Uppercut",
      "age": 39,
      "secretIdentity": "Jane Wilson",
      "powers": [
        "Million tonne punch",
        "Damage resistance",
        "Superhuman reflexes"
      ]
    },
    {
      "name": "Eternal Flame",
      "age": 1000000,
      "secretIdentity": "Unknown",
      "powers": [
        "Immortality",
        "Heat Immunity",
        "Inferno",
        "Teleportation",
        "Interdimensional travel"
      ]
    }
  ]
}

Arrays as JSON

An array is also valid JSON,

[
  {
    "name": "Molecule Man",
    "age": 29,
    "secretIdentity": "Dan Jukes",
    "powers": [
      "Radiation resistance",
      "Turning tiny",
      "Radiation blast"
    ]
  },
  {
    "name": "Madame Uppercut",
    "age": 39,
    "secretIdentity": "Jane Wilson",
    "powers": [
      "Million tonne punch",
      "Damage resistance",
      "Superhuman reflexes"
    ]
  }
]

Other notes

  • JSON is purely a data format — it contains only properties, no methods.
  • JSON requires double quotes to be used around strings and property names. Single quotes are not valid.
  • Even a single misplaced comma or colon can cause a JSON file to go wrong, and not work. You should be careful to validate any data you are attempting to use (although computer-generated JSON is less likely to include errors, as long as the generator program is working correctly). You can validate JSON using an application like JSONLint.
  • JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be a valid JSON object.
  • Unlike in JavaScript code in which object properties may be unquoted, in JSON only quoted strings may be used as properties.

Full JSON syntax


JSON = null
    or true or false
    or JSONNumber
    or JSONString
    or JSONObject
    or JSONArray

JSONNumber = - PositiveNumber
          or PositiveNumber
PositiveNumber = DecimalNumber
              or DecimalNumber . Digits
              or DecimalNumber . Digits ExponentPart
              or DecimalNumber ExponentPart
DecimalNumber = 0
             or OneToNine Digits
ExponentPart = e Exponent
            or E Exponent
Exponent = Digits
        or + Digits
        or - Digits
Digits = Digit
      or Digits Digit
Digit = 0 through 9
OneToNine = 1 through 9

JSONString = ""
          or " StringCharacters "
StringCharacters = StringCharacter
                or StringCharacters StringCharacter
StringCharacter = any character
                  except " or \ or U+0000 through U+001F
               or EscapeSequence
EscapeSequence = \" or \/ or \\ or \b or \f or \n or \r or \t
              or \u HexDigit HexDigit HexDigit HexDigit
HexDigit = 0 through 9
        or A through F
        or a through f

JSONObject = { }
          or { Members }
Members = JSONString : JSON
       or Members , JSONString : JSON

JSONArray = [ ]
         or [ ArrayElements ]
ArrayElements = JSON
             or ArrayElements , JSON

Methods

  • JSON.parse(text[, reviver])
  • The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
  • JSON.stringify(value[, replacer[, space]])
  • The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Active learning: Working through a JSON example

There are 3 files as the template:
  • heroes.html
  • 
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
    
        <title>Our superheroes</title>
    
        <link href="https://fonts.googleapis.com/css?family=Faster+One" rel="stylesheet">
        <link rel="stylesheet" href="style.css">
      </head>
    
      <body>
    
          <header>
    
          </header>
    
          <section>
    
          </section>
    
        <script>
        const header = document.querySelector('header');
        const section = document.querySelector('section');
    
    
    
        </script>
      </body>
    </html>
    
  • style.css
  • 
    /* || general styles */
    
    html {
      font-family: 'helvetica neue', helvetica, arial, sans-serif;
    }
    
    body {
      width: 800px;
      margin: 0 auto;
    }
    
    h1, h2 {
      font-family: 'Faster One', cursive;
    }
    
    /* header styles */
    
    h1 {
      font-size: 4rem;
      text-align: center;
    }
    
    header p {
      font-size: 1.3rem;
      font-weight: bold;
      text-align: center;
    }
    
    /* section styles */
    
    section article {
      width: 33%;
      float: left;
    }
    
    section p {
      margin: 5px 0;
    }
    
    section ul {
      margin-top: 0;
    }
    
    h2 {
      font-size: 2.5rem;
      letter-spacing: -5px;
      margin-bottom: 10px;
    }
    
  • superheroes.json
  • 
    {
      "squadName" : "Super Hero Squad",
      "homeTown" : "Metro City",
      "formed" : 2016,
      "secretBase" : "Super tower",
      "active" : true,
      "members" : [
        {
          "name" : "Molecule Man",
          "age" : 29,
          "secretIdentity" : "Dan Jukes",
          "powers" : [
            "Radiation resistance",
            "Turning tiny",
            "Radiation blast"
          ]
        },
        {
          "name" : "Madame Uppercut",
          "age" : 39,
          "secretIdentity" : "Jane Wilson",
          "powers" : [
            "Million tonne punch",
            "Damage resistance",
            "Superhuman reflexes"
          ]
        },
        {
          "name" : "Eternal Flame",
          "age" : 1000000,
          "secretIdentity" : "Unknown",
          "powers" : [
            "Immortality",
            "Heat Immunity",
            "Inferno",
            "Teleportation",
            "Interdimensional travel"
          ]
        }
      ]
    }
    
The completed source code heroes-finished.html :

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">

    <title>Our superheroes</title>

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Faster+One">
    <link rel="stylesheet" href="style.css">
  </head>

  <body>

      <header>

      </header>

      <section>

      </section>

    <script>
    const header = document.querySelector('header');
    const section = document.querySelector('section');

    let requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
    let request = new XMLHttpRequest();
    request.open('GET', requestURL);
    request.responseType = 'json';
    request.send();

    request.onload = function() {
      const superHeroes = request.response;
      populateHeader(superHeroes);
      showHeroes(superHeroes);
    }

    function populateHeader(jsonObj) {
      const myH1 = document.createElement('h1');
      myH1.textContent = jsonObj['squadName'];
      header.appendChild(myH1);

      const myPara = document.createElement('p');
      myPara.textContent = 'Hometown: ' + jsonObj['homeTown'] + ' // Formed: ' + jsonObj['formed'];
      header.appendChild(myPara);
    }

    function showHeroes(jsonObj) {
      const heroes = jsonObj['members'];

      for(let i = 0; i < heroes.length; i++) {
        const myArticle = document.createElement('article');
        const myH2 = document.createElement('h2');
        const myPara1 = document.createElement('p');
        const myPara2 = document.createElement('p');
        const myPara3 = document.createElement('p');
        const myList = document.createElement('ul');

        myH2.textContent = heroes[i].name;
        myPara1.textContent = 'Secret identity: ' + heroes[i].secretIdentity;
        myPara2.textContent = 'Age: ' + heroes[i].age;
        myPara3.textContent = 'Superpowers:';

        const superPowers = heroes[i].powers;
        for(let j = 0; j < superPowers.length; j++) {
          const listItem = document.createElement('li');
          listItem.textContent = superPowers[j];
          myList.appendChild(listItem);
        }

        myArticle.appendChild(myH2);
        myArticle.appendChild(myPara1);
        myArticle.appendChild(myPara2);
        myArticle.appendChild(myPara3);
        myArticle.appendChild(myList);

        section.appendChild(myArticle);
      }
    }

    </script>
  </body>
</html>
  • <link rel="stylesheet" href="" >
  • The HTML External Resource Link element (<link rel="stylesheet">) specifies relationships between the current document and an external resource. To link an external stylesheet, you'd include a <link> element inside your <head> .
  • Document.querySelector()
  • The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.
  • Obtaining the JSON from the server
  • There is a very useful JavaScript object XMLHttpRequest that allows us to make network requests to retrieve resources from a server via JavaScript (e.g. images, text, JSON, even HTML snippets).
    • prepare the URL of the JSON
    • 
      let requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
      
    • create a new request object instance from the XMLHttpRequest constructor
    • 
      let request = new XMLHttpRequest();
      
    • initialize the HTTP request
    • 
      request.open('GET', requestURL);
      
      
    • Sends the request.
    • 
      request.responseType = 'json';
      request.send();
      
      XHR knows that the server will be returning JSON by request.responseType.
    • setup the event handlers
    • 
      request.onload = function() {
        const superHeroes = request.response;
        populateHeader(superHeroes);
        showHeroes(superHeroes);
      }
      
      The load event fires when the response has successfully returned. This variable superHeroes now contains the JavaScript object based on the JSON. We are then passing that object to two function calls
      • Populating the header
      • 
        function populateHeader(jsonObj) {
          const myH1 = document.createElement('h1');
          myH1.textContent = jsonObj['squadName'];
          header.appendChild(myH1);
        
          const myPara = document.createElement('p');
          myPara.textContent = 'Hometown: ' + jsonObj['homeTown'] + ' // Formed: ' + jsonObj['formed'];
          header.appendChild(myPara);
        }
        
        • Document.createElement()
        • The document.createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.
        • Node.appendChild()
        • The Node.appendChild() method adds a node to the end of the list of children of a specified parent node.
      • Creating the hero information cards
      • 
        function showHeroes(jsonObj) {
          const heroes = jsonObj['members'];
              
          for (let i = 0; i < heroes.length; i++) {
            const myArticle = document.createElement('article');
            const myH2 = document.createElement('h2');
            const myPara1 = document.createElement('p');
            const myPara2 = document.createElement('p');
            const myPara3 = document.createElement('p');
            const myList = document.createElement('ul');
        
            myH2.textContent = heroes[i].name;
            myPara1.textContent = 'Secret identity: ' + heroes[i].secretIdentity;
            myPara2.textContent = 'Age: ' + heroes[i].age;
            myPara3.textContent = 'Superpowers:';
                
            const superPowers = heroes[i].powers;
            for (let j = 0; j < superPowers.length; j++) {
              const listItem = document.createElement('li');
              listItem.textContent = superPowers[j];
              myList.appendChild(listItem);
            }
        
            myArticle.appendChild(myH2);
            myArticle.appendChild(myPara1);
            myArticle.appendChild(myPara2);
            myArticle.appendChild(myPara3);
            myArticle.appendChild(myList);
        
            section.appendChild(myArticle);
          }
        }
        
        HTML5 offers new semantic elements to define different parts of a web page:
        
        <article>
        <aside>
        <details>
        <figcaption>
        <figure>
        <footer>
        <header>
        <main>
        <mark>
        <nav>
        <section>
        <summary>
        <time>
        

留言

熱門文章