JavaScript

Implementing Client-side Behaviour

Randy J. Fortier
randy.fortier@uoit.ca
@randy_fortier

Outline

  • JavaScript overview
  • Syntax
    • Basic contructs
    • Functions
    • Classes
    • API reference
    • Regular expressions
  • JavaScript in web pages
    • How to embed
    • User input
    • User output
    • Events
    • Debugging

JavaScript

An Overview

JavaScript Overview

  • Dynamic and loose typing
    • No need to declare variables
    • Can assign different types to the same variable
    • Can attach arbitrary properties to objects at run time
  • Similar syntax to Java, C, C++, C#
  • Generally Just-in-Time (JIT) compiled within the browser

JavaScript

Syntax

Variables and expressions


sum = 0;
numMarks = 0;
...
var average = sum / numMarks; 
                        

Conditionals

  • Same syntax as Java, C, C++, C#:

var num = ...;
if (num <= 10) {
   // small
} else if ((num > 10) && (num  <= 20)) {
   // medium
} else {
   // large
}
                        

While Loops

  • Same syntax as Java, C, C++, C#:
    • break: Exit from the loop
    • continue: Proceed to next loop iteration

var num = 10;
while (num > 0) {
   // do something
   num--;
}
                        

For Loops

  • Same syntax as Java, C, C++, C#:

for (var i = 0; i < 10; i++) {
   // do something
}
                        

Functions


function isPrime(number) {
   for (var div = 2; div < number/2; div++) {
      if ((number % div) == 0) {
         return false;
      } 
   }
   return true;
}
var is243Prime = isPrime(243);
                        

Anonymous Functions


var prime = function(number) {
   for (var div = 2; div < number/2; div++) {
      if ((number % div) == 0) {
         return false;
      } 
   }
   return true;
}
var is243Prime = prime(243);
                        

Recursive Functions


function fibonacci(n) {
   if (n == 0 || n == 1) {
      return n; 
   }
   return fibonacci(n - 1) + fibonacci(n - 2);
}
var fib10 = fibonacci(10);
                        

Arrays


var array1 = new Array();
array1[0] = 1;
array1[1] = 2;
var array2 = new Array('abc', 'def', 'ghi');
var array3 = [true, false, true];
var myarray1 = [3,1,,9,,2];  // has empty elements
var myarray2 = new Array(5); // all empty
for (var i = 0; i < array1.length; i++) {
   if (array1[i] == 9) {
      // do something
   }
}
                        

Arrays

  • Another notation for for loops over arrays:

var array1 = new Array();
array1[0] = 1;
array1[1] = 2;
for (var i in array1) {
   if (array1[i] == 9) {
      // do something
   }
}
                        

2D Arrays


var my2DArray1 = [[1,2,3],[4,5]];

var my2DArray2 = new Array(2);
my2DArray2[0] = new Array(3);
my2DArray2[1] = new Array(2);

var sum = 0;
for (var i = 0; i < my2DArray.length; i++ ) {
   for (var j = 0; j < my2DArray[i].length; j++) { 
      sum += my2DArray[i][j];
   }
}
                        

Dictionaries


var grades = {"100000001": "A",
              "100000013": "C",
              "100000015": "C-",
              "100000019": "B-",
              "100000022": "C-",
              "100000037": "C+",
              "100000051": "F",
              "100000059": "B+",
              "100000063": "F",
			  };
var sid = "100000037";
console.log("The grade of " + sid + " is " + grades[sid]);
                        

Objects


var Shape = function(x, y) {
	this.x = x;
	this.y = y;
	
	this.translate = function(dx, dy) {
		this.x += dx;
		this.y += dy;
	};
	
	this.toString = function() {
		return "[Shape " + this.x + ", " + this.y + "]";
	};
};
var shape = new Shape(30, 50);
shape.translate(10, -10);
console.log("shape: " + shape);
                        

Inheritance


var Shape = function(x, y) { /* as before */ };

var Circle = function(x, y, radius) {
	Shape.call(this, x, y);
	this.radius = radius;
	
	this.getArea = function() {
		return Math.PI * this.radius * this.radius;
	};
};

var circle = new Circle(0, 0, 1.0);
console.log("area: " + circle.getArea());
console.log("circle: " + circle);
                        

JavaScript

API Reference

API Reference: Strings


int position1 = str.indexOf('def');
int position2 = str.lastIndexOf('def');
int notThere = str.indexOf('aaa');
var str2 = str.replace("abc", "ABC"); // 1st
var str3 = str.slice(3, 6);
var str4 = str.substr(3, 3);
var str5 = str.toUpperCase();
var str6 = "the quick brown fox jumped over";
var words = str6.split(' ');
                        

API Reference: Math


var ceil = Math.ceil(7.5);
var floor = Math.floor(7.5);
var round = Math.round(7.5);
var sqrt = Math.sqrt(16);
var dieRoll = Math.floor(1 + Math.random() * 6);
function areaOfCircle(radius) {
  return Math.PI * Math.pow(radius, 2);
}
                        

API Reference: Arrays


var array1 = ["the", "quick", "brown"];
var array2 = ["fox", "jumped", "over", "the"];
var merged = array1.concat(array2);
var phrase = merged.join(' ');
var brown = array1.pop();
var array3 = array1.push("orange");
var the = array1.shift();
var array4 = array1.unshift("a");
var backwards = array1.reverse();
var quickbrown = array1.slice(1, 2);
var sorted = merged.sort();
var afastyellow = array4.splice(1, 1, "fast");
console.log('afastyellow: ' + afastyellow);
                        

API Reference: Dates


var rightNow = new Date();
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate()+1);
var halloween2008 = new Date(08,10,31);
var newYears2025 = new Date();
newYears2025.setFullYear(2025,01,01);
if (rightNow > newYears2025) {
  console.log('Happy new year!');
}
                        

JavaScript

Regular Expressions

Regular Expressions


var badWordsPattern = /darn|crud|gosh/;
var text5 = "It took me all day to write the gosh darned thing.";
if (text5.match(badWordsPattern)) {
   console.log("This post contains some bad words.");
}
                        

Regular Expressions

  • Replacing regular expressions

var costPattern = /\$[0-9]+/;
var text1 = 'I paid $100 for this item.';
var text2 = text1.replace(costPattern, '$...');
console.log(text2);
                        

Regular Expressions

  • Regular expression options
    • i: case insensitive
    • g: global (i.e. replace all occurrences)

var wordPattern = /the/ig;
var text3 = 'the quick brown fox jumped over the';
var match = text3.replace(wordPattern, 'a');
console.log(match);
                        

Regular Expressions

  • Validating with regular expressions

var emailPattern = /\w@\w[.\w]+/;

var email1 = 'rfortier@macrosoft.ca';
var email1Ok = emailPattern.test(email1);
if (email1Ok)
  console.log(email1 + ' is ok.');
var email2 = 'rfortier';
var email2Ok = emailPattern.test(email2);
if (email2Ok)
  console.log(email2 + ' is ok.')

                        

JavaScript

JavaScript in Web Pages

Embedding JavaScript

  • In the HTML:
    
    <!DOCTYPE html>
    <html lang="en">
      <head>
      </head>
      <body>
        <script type="text/javascript"
                src="simple.js"></script>
      </body>
    </html>
                                    
  • In the JS file:
    
    console.log("It worked!");
                                    

User Input

  • Retrieve data from a text field:

var field = document.getElementById('fname');
var fname = field.value;
                        

Programmer Output

  • Display information in the console:

console.log("person: " + person);
                        

User Output

  • Add content to a container DOM element:
    
    var element = document.getElementById('mydiv');
    element.innerHTML = 'hello';
                                    
  • Add a value to a DOM text field:
    
    var element = document.getElementById('fname');
    fname.value = 'Sally';
                                    

JavaScript

Event Handling

The Load Event

  • The Load event fires when the entire HTML document has been loaded and the DOM has been built

window.onload = function() {
    // do some initialization
};

Button Press Events

  • Called when the user clicks a button

var button = document.getElementById('loginButton');
button.onclick = function() {
    // do login
};

Dropdown Select Events

  • Called when the user changes their selection in a dropdown list

var dropdown = document.getElementById('country');
dropdown.onchange = function() {
    // update provinces or states
};

Event Objects

  • Event objects provide details about the event

var button = document.getElementById('loginButton');
button.onclick = function() {
  var event = window.event;
  var x = event.clientX;
  var y = event.clientY;
  // do something with x and y
}
                        

Event Objects

  • Important properties of the event object:

var button = document.getElementById('loginButton');
button.onclick = function() {
  var event = window.event;
  console.log(event.target);    // generating element
  console.log(event.type);      // e.g. onclick
  console.log(event.timeStamp); // when
}
                        

Events

  • Mouse events:
    • onmouseover – Mouse is over top of the rectangle bounding this element
    • onmouseout – Mouse has left the rectangle bounding this element
    • onclick – The user has clicked within the bounding rect.
    • ondblclick – As above, but a double-click
    • onmousedown – The mouse button was pressed down
    • onmouseup – The mouse button was released

Event Objects

  • For mouse events:

var div = document.getElementById('div');
div.onmousemove = function() {
  var event = window.event;
  console.log(event.screenX);   // absolute screen coordinates
  console.log(event.screenY);
  console.log(event.clientX);   // coordinates relative to the div
  console.log(event.clientY);
  console.log(event.button);    // which button
  console.log(event.altKey);    // was ALT pressed?
  console.log(event.ctrlKey);   // was CTRL pressed?
  console.log(event.shiftKey);  // was SHIFT pressed?
}
                        

Events

  • Keyboard events:
    • onkeydown – A keyboard key has been pressed down
    • onkeyup – A keyboard key is been released
    • onkeypress – A keyboard key has been pressed and released, as a keystroke

Event Objects

  • For keyboard events:

var div = document.getElementById('div');
div.onkeypress = function() {
  var event = window.event;
  console.log(event.keyIdentifier); // which key
  console.log(event.altKey);        // was ALT pressed?
  console.log(event.ctrlKey);       // was CTRL pressed?
  console.log(event.shiftKey);      // was SHIFT pressed?
}
                        

Events

  • Form events:
    • onsubmit– The form has been submitted (used for validation)
  • Form element events:
    • onfocus – The form element is now the active form element (e.g. the user clicks in a text field)
    • onblur – The form element is no longer the active form element
    • onchange – The value of the form element has changed (used for validation)

Wrap-Up

  • In this section, we learned about:
    • Basic constructs in JavaScript
    • Object-oriented programming
    • API reference
    • Regular expressions
    • Integrating JS into web pages
    • Handling events