JavaScript Notes

2020/07/21

JavaScript Notes

There are three ways of using JavaScript in HTML document.

External:

<head>
  <!-- import JavaScript in head -->
  <script src="index.js"></script>
<body>
  <!-- import JavaScript in body -->
  <script src="index.js"></script>
</body>

Internal:

<body>
  <script> // full form: <script type="text/javascript">
    <!-- JavaScript code here -->
  </script>
</body>

Inline:

<head>
  <script>
    function showAlert()
    {
        alert("Clicked on a button!")
    }
  </script>
</head>
<body>
  <!-- display an alert on button click -->
  <input type="button" value="aButton" onclick="alert('Whats up?')" />

  <!-- call another function -->
  <input type="button" value="anotherButton" onclick="showAlert()" />
</body>

Basics

Variables and Constants

var a = 10;
var b = 20, c = 30;
a = a + 1

// constants:
var DEBUG = 1;

Data Types

var number = 100;
var string1 = 'Single can be wrapped by single quote.'
var string2 = "String can also be wrapped by double quote."
var string3 = "String can have escape value like \" or \'."
if (number < 200) // boolean condition
{
    document.write("number is less than 200.")
}
// undefined:
var n;
document.write(n)
// null value
var m = null;

Operations

Operator Meaning
+ addition
- subtraction
* multiplication
/ division
% remainder
++ add one
minus one
= plain assignment
-= subtraction assignment
+= addition assignment
*= multiplication assignment
/= division assignment

Comparison

Operator Meaning
> greater than
< less than
>= greater than or equal to
<= less than or equal to
== equal to
!= not equal to

Logic Operation

Operator Meaning
&& AND
|| OR
! NOT

Condition Operation

var a = condition ? expression1 : expression2;

Type Conversion

Flow Control

if…else…

if (condition) {
    // statement
}

if (condition) {
    // statement1
} else {
    // statement2
}

if (condition1) {
    // statement1
} else if (condition2) {
    // statement2
} else {
    // statement3
}

switch

var day = 3;
var week;

switch (day)
{
    case 1:
        week = "Monday"; break;
    case 2:
        week = "Tuesday"; break;
    case 3:
        week = "Wednesday"; break;
    case 4:
        week = "Thursday"; break;
    case 5:
        week = "Friday"; break;
    case 6:
        week = "Saturday"; break;
    default:
        week = "Sunday";
}

loops

while (condition)
{
    // statement executed when condition is true
}
do
{
    // statement
} while(condition);
for (initial expression; condition; post-loop expression)
{
    // ...
}

// e.g.
for (var i = 0 ; i < 5 ; i++)
{
    // ...
}

Function

function name(argument1, argument2, , argumentN)
{
    // function body
    return value; // return a value if the function does have one
}
<script>
  // function that doesn't return
  function showMessage(msg)
  {
      document.write(msg)
  }
  showMessage("Hi") // direct invocation

  // function that returns
  function addSum(a, b)
  {
      var sum = a + b;
      return sum;
  }
  var n = addSum(1, 2) + 100; // function call as part of expression
  document.write(n);
</script>

<!-- function call as hyperlink -->
<a href="javascript:showMessage('Hello, world!')">Click Me</a>

<body>
  <!-- function call as an event -->
  <input type="button" onclick="showMessage('Submitted')" value="Submit" />
</body>

String Operation

Please look for more detailed documents on this top, below are just a few operations for string.

Array

To create an array in JavaScript:

var arrayName = new Array(element1, element2, , elementN); // full form
var arrayName = [element1, element2, , elementN]; // short form
var emptyArray = []; // empty array

arrayName[i] = value; // value assignment to index i

Date and Time

Create a new Date object:

var date = new Date();

Please refer to JavaScript documentation for functions of Date, basically it has a list of getXxx and setXxx for retrieving and setting details of the date.

Mathmatics

In JavaScript we can use Math object to perform a list of mathematical calculations. It has constants commonly used in Maths like PI, and functions like abs(x), floor(x), ceil(x) and random().

DOM

DOM stands for Document Object Model, the document structure is modeled as an object, different parts of the document can be read and manipulated through the concept of “node”, with three commonly used nodes:

<div id="wrapper">text</div>

Element Node

<ul id="list">
  <li>HTML</li>
  <li>CSS</li>
  <li>JavaScript</li>
  <li>jQuery</li>
</ul>
<body>
  Favourite Fruit:
  <label><input type="radio" name="fruit" value="Apple" />Apple</label>
  <label><input type="radio" name="fruit" value="Orange" />Orange</label>
  <label><input type="radio" name="fruit" value="Banana" />Banana</label>
</body>

document.title and document.body

JavaScript provides an easy way to access the title and body of document:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title></title>
  <script>
    window.onload = function()
    {
        document.title = "Title";
        document.body.innerHTML = "<p>A paragraph of text.</p>";
    }
  </script>
</head>
<body></body>
</html>

Create Element

In JavaScript we can dynamically create new elements and modify existings elements, this is called “Dynamic DOM Operation”.

Sample (add a strong text):

window.onload = function()
{
    var oDiv = document.getElementById("content");
    var oStrong = document.createElement("strong");
    var oText = document.createTextNode("Text");

    oStrong.appendChild(oText);
    oDiv.appendChild(oStrong);
}

Another sample, creating an image equivalent to HTML:

<img class="pic" src="images/photo.png" style="border:1px solid silver" />
window.onload = function()
{
    var oImg = document.createElement("img");
    oImg.className = "pic"; // className is used instead of class because class is a keyword
    oImg.src = "images/photo.png";
    oImg.style.border = "1px solid silver";
    document.body.appendChild(oImg);
}

DOM Advanced

HTML Attributes

Access attribute of object via: obj.attr, consider the following HTML code:

<input id="btn" type="button" value="Submit" />

To retrieve the button:

// get the button and assign it `onclick` function
var button = document.getElementById("btn")
button.onclick = function()
{
    alert(button.id);
};

To create the button dynamically:

var input = documenmt.createElement("input");
input.id = "submit";
input.type = "button";
input.value = "Submit";
document.body.appendChild(input);

input.onclick = function()
{
    alert(input.id);
};

For custom attribute we have to use getAttribute(name) and setAttribute(value, name), consider this code with custom attribute data:

<input id="btn" type="button" value="Insert" data="JavaScript" />

To retrieve data attribute:

var button = document.getElementById("btn");
button.getAttribute("data");
// button.data is undefined

DOM Traversal

Events

In JavaScript, an event consists of three parts: Subject, Type and Action. Please refer to JavaScript documentation for list of events for different elements.

Event Invocation

Trigger event in script tag:

object.eventName = function()
{
    // event body
};

e.g.

window.onload = function()
{
    // event body
};

Trigger event in element:

<input type="button" onclick="showAlert()" value="Alert" />

Event Listener

obj.addEventListener(type, function, false);
obj.removeEventListener(type, function, false);
window.onload = function()
{
    var button = document.getElementById("btn");
    button.addEventListener("click", function(){
        alert("First Click");
    }, false);
    button.addEventListener("click", function(){
        alert("Second Click");
    }, false);
    button.addEventListener("click", function(){
        alert("Third Click");
    }, false);
}

event object

An object for event is passed to event function.

Attribute Meaning
type type of event
keyCode code of key stroke
shiftKey if Shift key is pressed
ctrlKey if Ctrl key is pressed
altKey if Alt key is pressed

window object

In JavaScript, every browser window/tab is a window object, each window object has a list of sub-objects and methods. Please refer to JavaScript documentation for detailed explanation of children objects and methods.

Child objects of window:

sub object meaning
document document model of the page
location URL related object
navigator browser related object
history browsing history
screen screen related object

Methods of window:

method meaning
alert() show an alert dialog
confirm() show a confirmation dialog
prompt() show a prompt dialog
open() open a new window
close() close the window
setTimeout() turn on “once off” timer
clearTimeout() turn off “once off” timer
setInterval() turn on repeating timer
clearInterval() turn off repeating time