www.MichaelTague.com

JavaScript Summary and Examples

From w3schools tutorial

Most examples taken from w3schools JavaScript tutorial. Many are modified or contain additions

HTML code for a button invoking a JavaScript alert:
  <button type="button" onclick="alert('Ouch!')">Click Me</button>
  

Replace possibly empty labeled HTML using:
  document.getElementById('xyzzy').innerHTML = 'New Stuff'

First Javascript - Date Time Button

Replace Text


This will change an attribute of an image (light on/off)

Light Bulb

Uses:<img id="myImage" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180"> <script> function changeImage() { var image = document.getElementById('myImage'); if (image.src.match("bulbon")) { image.src = "pic_bulboff.gif"; } else { image.src = "pic_bulbon.gif"; } } </script>

This kind of function can change the style:

function myFunction() { var x = document.getElementById("demo"); x.style.fontSize = "25px"; x.style.color = "red"; }

Style Change

Validate

JavaScript can be inserted between <script> and </script> in the <body> or <head> sections. The attribute type="text/javascript" is no longer required as JavaScript is the default scripting language for HTML.

It is a good idea to put scripts in the bottom of the body so that HTML display can occur earlier. Or, in external scripts: <script src="myScript.js"></script> where it may be easier to maintain both the scripts and the HTML.

Different forms of output:
  window.alert() - pop up window
  document.write() - write in-line*
  innerHTML() - write to a section
  console.log() - to the console
* document.write() will replace the entire HTML if invoked after loading. Just use for debugging.

JavaScript is case sensitive. Variable names are often camelCased. Number can apper with or without a decimal: 14, 12.2, comments are "//" or "/* */", variables are declared with the var keyword. Assignment is =, and arithmetic is + - * /. Semicolons and braces are used (semicolons are optional).

Some statements: break; continue; debugger; do ... while; for; function; if ... else; return; switch; try ... catch, var.

Identifies (variable names) are case sensitive consisting of letters, numbers, underscores, or dollar signs. Identifiers cannot start with a number.

Strings can appear in single or double quotes. = is for assignment, == for tests. It is good practice to delare variables at the beginning of a script. The var statment can have multple variables declared separated by commas, e.g., var x = 3, y = 4; An uninitialized variable has the value of undefined. A variable can be re-declared, but will not loose its value. String addition is concatenation. "5" + 2 + 3 == "523".

Arith Operators: + - * / % ++ --. Assignment: = += -= *= /= %=

Data types: number, string, boolean, array(list in []), object(name:value pairs in a list using {}). Variables have dynamic typing: x = 5; x = "foo";. Nums can be sci notation: 3e5, 4e-2. typeof operator exists and can return undefined, also, an array is just considered an object.

Functions look like this: function factorial(n) { if(n <= 1) { return 1; } else { return n*factorial(n-1); } } Interestingly while "factorial(4)" will return the expected result of 24, "factorial" will return the code of the factorial function!

Object component access, two ways: thing.myVar, or thing["myVar"]. Scope: local when declared in fuctions, global otherwise. Global to the javascript environment, and global to a web page within a web broswer. Also, variables used but not declared (no var ...) will automatically be global. The web page window variables and javascript variables share the same name space and can overwrite each other.

Events: button clicked, page finished loading, input field changed. Can trigger javascript calls. onchange, onclick, onmouseover, onmouseout, onkeydown, onload. More: DOM Events Example: $lt;button onclick="this.innerHTML=Date()">The time is?</button>

String: length property, e.g., myString.length. Escape: \, \\, \n, \r, \t, \b (backspace), \f (formfeed), \(real newline). Strings can be created as objects: new String("Test"), but not a good idea. === tests for value equality and type equality. String properties: constructor (returns function that created String's prototype, length, prototype. Methods: charAt(), charCodeAt(), concat(), fromCharCode(), indexOf() - first occurance, lastIndexOf() - last occurance, localeCompare(), match(), replace(), search(), slice(), split(), substr(), substring(), toLocaleLowerCase(), toLocaleUpperCase(), toLowerCase(), toString(), toUpperCase(), trim(), valueOf(). 0 to N string position. Negative values count from the right. -1 for not found. split() will create an array from a string. Don't treat a string as an array (though it will work in some instaces).

Numbers: all stored as 64 bit floating point (52 bit mantissa, 11 bit exponent, 1 bit sign.d. About 15 digits of accuracy. Hex: 0xFF; Use toString to display in different base: var myNum = 24; myNum.toString(16); base 16. Infinity, -Infinity, NaN are valid. Use isNaN(). typeOf (NaN, Infinity, -Infinity) is number. Properties: MAX_VALUE, MIN_VALUE, NEGATIVE_INFINITY, NaN, POSITIVE_INFINITY. E.g., var x = Number.MAX_VALUE;

Global methods: Number(), parseFloat(), parseInt(); Number methods: toString(), toExponential(), to Fixed(), to Precision(), valueOf(). Use: (123).toString(), not 123.toString(). Math: Math.random(), Math.min(), Math.max(), Math.round(), ceil(), floor(), log(), sin(), acos(), abs(), pow(), sqrt(), and others.

Dates: Date(), or new Date(), new Date(millis), new Date(dateString), new Date(year, month, day, hours, minutes, seconds, millis); .toString(), .toUTCString, .toDateString(), .getDate(), .getDay(), .getFullYear(), .getHours(), .getMilliseconds(), .getMinutes(), .getMonth(), .getSeconds(), .getTime(), .setDate(), .setFullYear(), .setHours(), .setMilliseconds(), .setMinutes(), .setMonth(), .setSeconds(), setTime(), .parse(). Months are counted 0 to 11.

Arrays: var cars = ["Ford", "Chevy", "Chrysler"]; var cards = new Array("Jack", "Queen"); Use first form. cars.length works, so does cards.sort(). Zero based arrays. Potentially useful: function isArray(myArray) { return myArray.constructor.toString().indexOf("Array") > -1; } .toString() and .valueOf() do the same thing for an array. .join() is interesting. var ip = [216, 24, 27, 3]; ip.join("."). .pop(), .push(), .shift() - removed 1st element and shuffles down the rest, .unshift(), splice(). push(thing) is the same as foo[foo.length] = thing. delete foo[0] makes foo[0] undefined. .reverse(). sort() can be passed a compare function: foo.sort(function(a, b){return a-b}) using -1,0,1 return.

Boolean: 0 (or -0, "", undefined, NaN, null, false) is false, everything else is true.

Logic: &&, ||, !. (condition) ? val1:val2; &, |, ~, ^ (xor), <<, >> based upon 32 bit signed numbers.

Labels, if, else, else if, while, do while, for, switch case defualt, continue, break, are identical to Java. "for (x in person)" will loop through properties of an object.

typeof: string, number, boolean, object, function. Arrays are also objects and values set to null are also objects. typeof undefined returns undefined. null == undefined is true, while null === undefined is not because null is an object and undefined is of type undefined.

Conversions: .toString(), String(foo), Number(foo), unary +, e.g., var a = "4", var b = + a; (converts to number).

RegExp: /pattern/modifiers Exp: foo.replace(/ed/i, "Curt"); Note: the RegExp is not a string, though you can use one for that. Modifiers: i (case insensitive), g (global), m (multiline). Some reg exp stuff: [abc], [0-9], (x|y), \d (digit), \s (whitespace), \b (begin/end of word), \uxxxx unicode. n+ (one or more), n* (zero or more), n? (zero or one). .test(), e.g., /e/.test("this test"); returns true since e is in "this test". .exec() returns the matched string.

Throw & try. try { stuff } catch(err) { } finally { }. You can also throw "whatever" or throw 344, that is, make up your own thing to throw..

Debugging. debugger command to invoke debugger. Also use console.log("stuff").

Hoisting. Javascrpt declarations are moved to the top of the current scope (though not the initialization).

"use strict" is a new feature, will not allow vars to be used before declared. Used globally or in a local scope. Use at beginning of scope.

Style: variable and function names camelCaseing. Global vars uppercase, constants uppercase. Spaces around operators. Code indentation. Use lower case file names.
Best Practice: avoid global vars. Always declare local vars. Declarations on top. Never declare numbers, strings, or booleans as objects. Use === comparisions. Missing arguments create undefined variables, assign default values, such as: y = y || 0. Don't use eval().
Beware assignment versus comparisions. Switch statements use strict comparisions (===). Carefull: 10 + 5 versus 10 + "5". Beware that JavaScript will automatically complete a statement so be careful where you break it: var x = 3; //OK return x; //Not OK, same as return; x; Delay JavaScript loading by putting scripts at bottom of page. You can use 'defer = "true"' in a script tag to delay loading of external scripts. Don't use the with keyword.

Standards: ECMAScript 3 (ES3) dates to 1999. ES5 from 2009.

JSON - JavaScript Object Notation. Often used to send data to a web page. JSON is standard accross many languages but uses JavaScript notation, but it is just text. E.g., "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Sydney", "lastName":"Tague"} {"firstName":"Max", "lastName":"Tague"} ] can use JSON.parse(text). Note: above would need to be wrapped in { } to make it parsable. If you did, you could do this: obj = JSON.parse(text); obj.employees[1].firstName + " " + obj.employees[1].lastName; which would be equal to "Sydney Tague".

JS Forms

Form validation is possible. 

Input a number between 10-20 or outside that range.

JS Objects

Dates, Maths?, Reg-Exp, Arrays, Functions, are all objecdts. All but numbers, strings, true, false, null, and undefined. Objects are an unordered collection of named values (properties and their values).

Creating an object. Preferred way: var person = {firstName:"Max", lastName:"Stewart"}; Or not preferred: var person = new Object(); person.firstName = "Max"; person.lastName = "Stewart"; Or use a constructor: function with name of object: function person(first, last) { this.firstName = first; this.lastName = last; } var myMother = new person("Margurite", "Tague"); var myFather = new person("Bob", "Tague"); Built-in object constructors: Object(), String(), Number(), Boolean(), Array(), RegExp(), Function(), Date().

Accessing properties: person.firstName, person["firstName"], or person[x]

Looping: for(x in person) { ... }

Adding/Deleting. Add: simply use it: person.age = 19. To delete, use: delete person.age; or delete person["age"];

Properties also have attributes, like: enumerable, configurable, writable.

Object method, e.g., var person = { firstName: "Witt", lastName: "Wilkinson", fullName: function() { return this.firstName + " " + this.lastName; } } Prototypes. All objects inherit from Object.prototype; To create a prototype, just make a function constructor, then you can use new to create an object of that type.

You can add a property or method to an existing object just be assigning it: person.eyeColor = "green"; You can add to a prototype: person.prototype.age = undefined; Example: function person(first, last) { this.firstName = first; this.lastName = last; } person.prototype.age = undefined; Which is the same as this: function person(first, last) { this.firstName = first; this.lastName = last; this.age = undefined; } You can also add a method (note no name): person.prototype.fullName = function () {return this.firstName + " " + this.lastName}

Functions

Functions are defined with the function keyword, but also can be defined as an expression:
  var x = function(a, b) {return a * b};
  var z = x(3, 4);
This function is anonymous (it has no name).

Functions can also be defined with a function constructor:
  var myFun = new Function("a", "b", "return a * b");
which is the same as the function assigned to x above.

Function declarations like variable declarations are hoisted to the top of the scope. Functions can be called before they are declared.

Self Invoking. A function expression surrounded by parens and followed by parens will invoke automatically. var x = function() {y = "Hello!"}; (x)(); console.log(y); These can be combined: (function() {y = "Hello!"})(); Functions are typeof function, but also have properties and methods like objects. E.g., arguments.length; myFun.toString(); Parameters. Pass by value, though objects are references to objects. No data types specified, no type checking performed, number of arguments is not checked; missing arguments set to undefined.

arguments: Functions have built-in arguments object. E.g., arguments[1] is the 2nd argument passed to the functions.

"this" refers to the object that owns the current code. In web pages, that is the web page (also called the window object). myFun() and window.myFun() are the same function; return this, returns the global (window) object.

new myFun() is a constructor invocation. It creats and object, any elements created in the function using "this" will be elements in the new object.

call() and apply() are predefined. Example use: function mul(x, y) { return x * y; } &nbsp;&nbsp;mul.call(myObject, 10, 2); //First arg is owner object &nbsp;&nbsp;mul.apply(myObject, argArray); Closures. All functions have access to global scope and to their own local scope. They also have access to their parent's scope if they are a function defined within a function A closure is a function that has access to its parent's scope even after the parent has closed. Example: var add = (function () { var counter = 0; return function () {return counter +1;} })(); //self-invoking function returns add function add(); //returns 1 add(); //returns 2 add(); //returns 3

HTML DOM

JavaScript can change/add/delete all HTML elements/attributes/CSS styles used in an HTML page. W3C DOM has three parts: Core DOM, XML DOM, HTML DOM.

HTML DOM. Standard object model and api for HTML. It defines HTML elements as objects, properties for all HTML elements, methods to access HTML elements, and events for all HTML elements.

document.getELementById("name").innerHTML = "Hello"; getElementById() is a method, and innerHTML is a property. The innerHTML property allows one to get or change the any HTML element (including or ). The document object owns the HTML page.

Finding HTML Elements

document.getElementById(), getElementsByTagName(), getElementsByClassName()

Changing HTML Elements

element.innerHTML =,element.attribute =, .setAttribute(attribute,value), .style.property =

Adding and Deleting Elements

document.createElement(), .removeChild(), .appendChild(), .replaceChild(), .write(text)

Adding Event Handlers

document.getLEementById(id).onclick=function() {code}

Finding HTML Objects

document.anchors, .baseURI, .body, .cookie, .doctype, .documentElement, .documentMode, .documentURI, .domain, .embeds, .forms, .head, .images, .implementation, .inputEncoding, .lastModified, .links, .readyState, .referrer, .scripts, strictErrorChecking, .title, .URL

Changing attributes

Example: <img id="myImage" src="smiley.gif"> <button type="button" onclick="change()">Click</button> <script> function change() { var image = document.getElementById('anImage'); if (image.src.match("smiley")) { image.src = "landscape.jpg"; } else { image.src = "smiley.gif"; } } <script>

This is black until you click the button
document.getElementById('anId').style.color = "blue"

Event listeners can be added (allows multiple listeners and avoids replacing existing listeners). They are named for the event: click, mouseover, etc. Multiple events can be added. If you need to pass arguments to the funciton, call it from within an anonymous function such as "function() { myFun(p1, p1);}". You can specify the whether it uses Bubbling (events in inner elements first, then outer elements) or Capturing (event handled outer then inner): addEventListener(event, function, false/true); false is default and is bubbling. document.getElementById("myBtn").addEventListener("click", doSomething); document.getElementById("myBtn".removeEventListener("click", doSomething);

Nodes. Use: parentNote, childNodes[nodeNumber], firstChild, lastChild, nextSibling, previousSibling. Note: common error is expecting all elements to have text, <title> doesn't, it points to a text node that does. document.body (the full body), document.documentElement (the full document).

nodeType is 1 (element), 2 (attribute), 3 (text), 8 (comment), 9 (document).

New elements can be added, e.g, var para = document.createELement("p"); var node = document.createTextNode("This is new"); para.appenChild(node); document.getELementById("div1").appendChild(para);

Removing elements. Find its parent, then remove the child. E.g. var child document.getElementById('p1'); child.parentNode.removeChild(child); replaceChild() is also available.

.getElementsByTagName("p"); returns a list of nodes.

Browser Object Model (BOW)

Window. Thr browser's window. All global objects, functions, and variables are members of the window object. So is document.

Window size. Not standard, new version window.innerHeight, window.innerWidth, though this will getnerall do it: var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; Screen. screen.width (in pixels), screen.height, screen.availWidth, screen.availHeight, screen.colorDepth (in bits)

window.history.back() - same as back button, window.history.forward() - same as forward button.

window.navigator (window prefix not needed).
  navigotor.cookieEnabled (none 1)
  navigator.appName (none 2)
  navigator.appCodeName (none 3)
  navigator.product (none 4)
  navigator.appVersion (none 5)
  navigator.platform (none 6)
  navigator.language (none 7)
  navigator.javaEnabled() (none 8)

Three kinds of popups: alert, Confirm, Prompt. window prefix is optional.


setInterval(), clearInterval() - for repeating a function.
setTimeout(), clearTimeout() - for starting a function after an interval.

Cookies are name/value pairs. You can use document.cookie to create them or delete them. Examples of how:

  document.cookie="username=Michael Tague";
  document.cookie="username=Michael Tague; expires Thr, 18 Dec 2015 12:00:00 UTC";
  document.cookie="username=Michael Tague; expires Thr, 18 Dec 2015 12:00:00 UTC; path=/";
  var x = document.cookie; //returns all cookies
  document.cookie="username=Michael Tague; expires Thr, 01 Jan 1970 00:00:00 UTC"; //deletes since exp date is old

Javascript Frameworks

JQuery, Prototype, MooTools, Dojo, Yahoo! YUI.

Google operates a Content Delivery Network (place to pull common scripts from). Example: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>