You are on page 1of 30

<!

doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="jstut.js"></script>

<style type="text/css">
body {font-size: 1.6em;}
.hidden {display:none;}
.show {display:inline !important;}
button {
border: 2px solid black; background: #E5E4E2;
font-size: .5em; font-weight: bold; color: black;
padding: .8em 2em;
margin-top: .4em;
}
</style>

</head>
<body>
<p id="sayHello"></p>
<script>

// You create variables that store values with var


// Prompt opens a popup that requests info
var yourName = prompt("What is your name?");

// If performs different actions depending on conditions


if(yourName != null){

// Set text in an HTML element with the id sayHello


// You concatenate (combine) strings with +
document.getElementById("sayHello").innerHTML = "Hello " + yourName;
} else {

// Alert opens a popup that contains a message


alert("Please Enter Your Name Next Time");
}

// ---------- VARIABLES ----------


// variable names can't start with a number, contain spaces, but can
// contain letters, numbers, underscores or $ (Are case sensitive)
var myName = "Derek";
var myAge = 40;

// Variables don't have a defined type, which can cause problems


myName = 100;

// ---------- MATH ----------


// document.write outputs data to the browser
document.write("5 + 4 = ", 5 + 4, "<br/>");
// Using + instead of , will treat everything as a string unless you use ()
document.write("5 + 4 = " + (5 + 4) + "<br/>");

document.write("5 - 4 = ", 5 - 4, "<br/>");


document.write("5 * 4 = ", 5 * 4, "<br/>");
document.write("5 / 4 = ", 5 / 4, "<br/>");

// Modulus remainder of a division


document.write("5 % 4 = ", 5 % 4, "<br/>");

var maxNum = Number.MAX_VALUE;

document.write("Max Num = ", maxNum, "<br/>");


document.write("Min Num = ", Number.MIN_VALUE, "<br/>");

// Numbers have 16 digits of precision


precisionTest = 0.1000000000000001;
document.write(precisionTest + 0.1000000000000001, "<br/>");

// Round number to 2 decimal places


var balance = 1563.87;
document.write("Monthly payment : ", (balance / 12).toFixed(2), "<br />");

var randNum = 5;

// Shortcut for adding 1


document.write("randNum++ = ", randNum++, "<br/>");
document.write("++randNum = ", ++randNum, "<br/>");

// The same exists for -


document.write("randNum-- = ", randNum--, "<br/>");
document.write("--randNum = ", --randNum, "<br/>");

// Perform a calculation on a value and assign the result


document.write("randNum += 5 = ", randNum += 5, "<br/>");
document.write("randNum -= 5 = ", randNum -= 5, "<br/>");
document.write("randNum *= 5 = ", randNum *= 5, "<br/>");
document.write("randNum /= 5 = ", randNum /= 5, "<br/>");

// Order of operations
document.write("3 + 2 * 5 = ", 3 + 2 * 5, "<br/>");
document.write("(3 + 2) * 5 = ", (3 + 2) * 5, "<br/>");

// Math properties and methods


document.write("Math.E = ", Math.E, "<br/>");
document.write("Math.PI = ", Math.PI, "<br/>");

document.write("Math.abs(-8) = ", Math.abs(-8), "<br/>");


document.write("Math.cbrt(1000) = ", Math.cbrt(1000), "<br/>");
document.write("Math.ceil(6.45) = ", Math.ceil(6.45), "<br/>");
document.write("Math.floor(6.45) = ", Math.floor(6.45), "<br/>");
document.write("Math.round(6.45) = ", Math.round(6.45), "<br/>");
document.write("Math.log(10) = ", Math.log(10), "<br/>"); // Natural log
document.write("Math.log10(10) = ", Math.log10(10), "<br/>"); // Base 10 log
document.write("Math.max(10,5) = ", Math.max(10,5), "<br/>");
document.write("Math.min(10,5) = ", Math.min(10,5), "<br/>");
document.write("Math.pow(4,2) = ", Math.pow(4,2), "<br/>");
document.write("Math.sqrt(1000) = ", Math.sqrt(1000), "<br/>");

document.write("Random # (1-10) = ", Math.floor((Math.random() * 10) + 1), "<br/>");

// Convert strings to numbers


document.write("Converted String : ", Number("3.14"), "<br />");

document.write("Converted Int : ", parseInt("5"), "<br />");


document.write("Converted Float : ", parseFloat("5.555"), "<br />");

// ---------- STRINGS ----------


var randStr = "A long " + "string that " + "goes on and on";

// String length
document.write("String Length : ", randStr.length + "<br/>");

document.write("Index for \"goes\" : ", randStr.indexOf("goes"), "<br/>");

// Return the value using a start and end index


document.write(randStr.slice(19, 23) + "<br/>");

// Return everything after the start index


document.write(randStr.slice(19) + "<br/>");

// Return the value using the start index and length


document.write(randStr.substr(19, 4) + "<br/>");

// Replace a string
document.write(randStr.replace("and on", "forever") + "<br/>");

// Get character at an index


document.write("At Index 2 : ", randStr.charAt(2) + "<br/>");

// Split a string into an array


var randStrArray = randStr.split(" ");

// Trim white space


randStr = randStr.trim();

// Convert to uppercase
document.write(randStr.toUpperCase() + "<br/>");

// Convert to lowercase
document.write(randStr.toLowerCase() + "<br/>");

// Styling with JS
var strToStyle = "Random String";
document.write("Big : ", strToStyle.big(), "<br />");
document.write("Bold : ", strToStyle.bold(), "<br />");
document.write("Font Color : ", strToStyle.fontcolor("blue"), "<br />");
document.write("Font Size : ", strToStyle.fontsize("8em"), "<br />");
document.write("Italics : ", strToStyle.italics(), "<br />");
document.write("Google : ", strToStyle.link("http://google.com"), "<br />");
document.write("Small : ", strToStyle.small(), "<br />");
document.write("Strike : ", strToStyle.strike(), "<br />");
document.write("Sub : ", strToStyle.sub(), "<br />");
document.write("Sup : ", strToStyle.sup(), "<br />");

// ---------- CONDITIONALS ----------


// Relational Operators : == != > < >= <=
// === : Equal value and type
// Logical Operators : && \\ !

var age = 8;

if ((age >= 5) && (age <= 6)){


document.write("Go to Kindergarten<br />");
} else if (age > 18) {
document.write("Go to College<br />");
} else {
document.write("Go to Grade ", age - 5, "<br />");
}

document.write("true || false = ", true || false, "<br />");

document.write("!true = ", ! true, "<br />");

document.write("\"5\" == 5 = ", ("5" == 5), "<br />");

document.write("\"5\" === 5 = ", ("5" === 5), "<br />");

// Switch is used to match a limited number of options


switch(age) {
case 5 :
case 6 :
document.write("Go to Kindergarten<br />");
break;

case 7 :
document.write("Go to 1st Grade<br />");
break;

default :
document.write("Subtract 5 from your age<br />");
}

// Ternary Operator assigns a value based on a condition


// (condition) ? iftrue : ifFalse
var canIVote = (age >= 18) ? true : false;

document.write("Can I Vote : ", canIVote, "<br />");

// ---------- LOOPING ----------

// while loops as long as a condition is true


var i = 1;
while (i <= 10){
document.write(i, ", ");
i++;
}
document.write("<br />");

// do while is used when you must go through the loop at least once
do{
var guess = prompt("Guess a number between 1 and 20");
}while(guess != 15)

alert("You guessed it! 15 was the number");

// for is a self contained looping structure


for(j = 0; j <= 20; j++){

// If j is divisible by 2 then skip back to the top of the loop


if((j % 2) == 0){
continue;
}

// If j is equal to 15 break completely out of the loop


if(j == 15){
break;
}
document.write(j, ", ");
}
document.write("<br />");

var customer = {name : "Bob Thomas", address : "123 Main", balance : 50.50};

// for in cycles through an enumerable properties of an object


for(k in customer){
document.write(customer[k], "<br />");
}

// ---------- ARRAYS ----------


// Arrays have variable sizes and can contain multiple types in JS
var tomSmith = ["Tom Smith", "123 Main", 120.50];

// Access first array item


document.write("1st State : ", tomSmith[0], "<br />");
// Add an item
tomSmith[3] = "tsmith@aol.com";

// Overwrite index 2 and fit everything else after index 2 without


// overwriting (Put 0 for second parameter to not overwrite)
tomSmith.splice(2, 1, "Pittsburgh", "PA");

// Delete the 4th index item


tomSmith.splice(4,1);

// Convert an array into a string (Also use toString())


document.write("Array : ", tomSmith.valueOf(), "<br />");

// Convert an array into a string with separator


document.write("Array : ", tomSmith.join(", "), "<br />");

// Delete an index
delete tomSmith[3];

// Sort an array (reverse() for reverse sort)


// Works for sorting strings
tomSmith.sort();

// Sort numbers
var numbers = [4,3,9,1,20,43];

// Descending sort return y - x


numbers.sort(function(x,y){ return x - y });
document.write("Num Array : ", numbers.toString(), "<br />");

// Combine arrays
var combinedArray = numbers.concat(tomSmith);

// Remove the last item


tomSmith.pop();

// Add items to the end


tomSmith.push("555-1212", "US");

// Deletes the first item


tomSmith.shift();

// Adds item to the first index


tomSmith.unshift("Tom Smith");

for (var i = 0; i < tomSmith.length; i++) {


document.write(tomSmith[i], "<br />");
}

// ---------- FUNCTIONS ----------


// Functions provide code reuse and eliminate repetitive code
// Define a function that checks if a value is in an array
function inArray(arrayToCheck, value){
for(i = 0; i < arrayToCheck.length; i++){
if(arrayToCheck[i] === value){
return true;
}
}
return false;
}

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

document.write("In Array : ", inArray(randArray, 4), "<br />");

// Local variables defined in functions can't be accessed outside of


// the function

function times2(num){
var var2 = 2;
return num * var2;
}

// Causes Error : document.write("Val of var2 : ", var2, "<br />");

// Pass a function as a parameter


function times3(num){
return num * 3;
}

function multiply(func, num){


return func(num);
}

document.write("3 * 15 = ", multiply(times3, 15), "<br />");

// Define a function expression


// We can assign functions to variables, store them in arrays,
// pass them into other functions and return them from functions
var triple = function(num){
return num * 3;
};

document.write("3 * 45 = ", multiply(triple, 45), "<br />");

// Receive variable number of arguments


function getSum(){
var sum = 0;
for(i = 0; i < arguments.length; i++){
sum += arguments[i];
}
return sum;
}
document.write("Sum : ", getSum(1,2,3,4,5), "<br />");

// Return a variable number of values


function times2(theArray){

var newArray = [];


for(i = 0; i < theArray.length; i++){
newArray.push(theArray[i] * 2);
}
return newArray;
}

document.write("Array Doubled : ", times2([1,2,3,4,5]).toString(), "<br />");

// Recursive Function
function factorial(num){
if(num <= 1){
return 1;
} else {
return num * factorial(num - 1);
}
}

document.write("Factorial of 4 : ", factorial(4), "<br />");

// 1st: num = 4 * factorial(3) = 4 * 6 = 24


// 2nd: num = 3 * factorial(2) = 3 * 2 = 6
// 3rd: num = 2 * factorial(1) = 2 * 1 = 2

// ---------- EVENT HANDLING ----------


function openAlert(mess){
alert(mess);
}

// ---------- DATE ----------


// Get a Date object
var curDate = new Date();

document.write("Date : ", curDate.getDate(), "<br />");


document.write("Month : ", curDate.getMonth(), "<br />");
document.write("Day : ", curDate.getDay(), "<br />");
document.write("Year : ", curDate.getFullYear(), "<br />");
document.write("Time : ", curDate.getHours(), ":", curDate.getMinutes(),
":", curDate.getSeconds(), ":", curDate.getMilliseconds(), "<br />");

// Create a Date object for my birthday


var myBD = new Date("December 21, 2015");

var msForBD = myBD.getTime();


var timeNow = curDate.getTime();
var tilMyBD = msForBD - timeNow;

document.write("Days til Birthday : ", tilMyBD / (1000 * 60 * 60 * 24), "<br />");

</script>

<!-- ---------- CHANGING ELEMENTS & EVENT HANDLING ---------- -->


<!-- All the events can be found here http://www.w3schools.com/jsref/dom_obj_event.asp -->

<!-- Open alert on click -->


<a href="JavaScript:void(0)" onClick="alert('Hello');">Say Hello</a><br />

<!-- Call a function on click -->


<a href="JavaScript:void(0)" onClick="openAlert('Hi how are you');">Say
Something</a><br />

<!-- Change text color on mouse rollover and roll out-->


<a href="JavaScript:void(0)" onmouseover="this.style.color='red';"
onmouseout="this.style.color='blue';"
ondblclick="this.text='You Double Clicked Me'"
onmousedown="this.text='Don\'t Press So hard'"
onmouseup="this.text='Thank You'">Make me Red</a><br />

<!-- Get value in an input element and open alert on change -->
<input type="text" id="randInput"
onChange="var dataEntered=document.getElementById('randInput').value; alert('User
Typed ' + dataEntered);"><br /><br />

<!-- When a user clicks a key provide info on the key clicked -->
<form action="#" id="sampForm">
<input id='charInput' type="text">
<p id="keyData">Key Data Here</p>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form><br /><br />

<img src="ntt-logo.png" id="logo">


<button id="logoButton">Get Logo</button><br />
<input id='mouseInput' type="text" size="30"><br />

Mouse X: <input type="text" id="mouseX"><br />


Mouse Y: <input type="text" id="mouseY"><br />

<button id="clearInputs">Clear Inputs</button><br />

<script>

function getChar(event) {

// event.which returns the key or mouse button clicked


if (event.which == null) {
// Return the char if not a special character
return String.fromCharCode(event.keyCode); // IE
} else if (event.which!=0 && event.charCode!=0) {
return String.fromCharCode(event.which); // Other Browsers
} else {
return null; // Special Key Clicked
}
}

document.getElementById('charInput').onkeypress = function(event) {
var char = getChar(event || window.event)
if (!char) return false; // Special Key Clicked

document.getElementById('keyData').innerHTML = char + " was clicked";


return true;
}

// Change text when the input gains focus


document.getElementById('charInput').onfocus = function(event) {
document.getElementById('keyData').innerHTML = "Input Gained Focus";
}

// Change text when the input loses focus


document.getElementById('charInput').onblur = function(event) {
document.getElementById('keyData').innerHTML = "Input Lost Focus";
}

// Change text when text is selected


document.getElementById('charInput').onselect = function(event) {
document.getElementById('keyData').innerHTML = "Text Selected";
}

// Add a listener that triggers a function on browser resize


window.addEventListener("resize", browserResized);

function browserResized() {
document.getElementById('keyData').innerHTML = "I've been resized";
}

// Make image invisible on click


document.getElementById('logo').onclick = function(event) {

// Change the class for the image


document.getElementById('logo').className = "hidden";

// Change the input element value


document.getElementById('mouseInput').value = "Clicked on image with button " +
event.button;
}

// Make image visible on click


document.getElementById('logoButton').onclick = function(event) {
document.getElementById('logo').className = "show";
}

// Change image src on mouseover


document.getElementById('logo').onmouseover = function(event) {
document.getElementById('logo').src = "ntt-logo-horz.png";
document.getElementById('mouseInput').value = "Mouse Over image";
}

// Change image src back on mouseout


document.getElementById('logo').onmouseout = function(event) {
document.getElementById('logo').src = "ntt-logo.png";
document.getElementById('mouseInput').value = "Mouse Left image";
}

// Get mouse x y coordinates


document.body.onmousemove = function(e) {
e = e || window.event;

// Get pageX, pageY : Mouse position relative to the html doc


var pageX = e.pageX;
var pageY = e.pageY;
if (pageX === undefined) {

// clientX, clientY : Mouse position relative to the browsers viewport


// scrollLeft, scrollTop : Pixels an element is scrolled left or
// from the top
pageX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
pageY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}

document.getElementById('mouseX').value = pageX;
document.getElementById('mouseY').value = pageY;
};

// Clear all input elements


document.getElementById('clearInputs').onclick = function(event) {
var inputElements = document.getElementsByTagName('input');

for (var i = 0; i < inputElements.length; i++) {


if (inputElements[i].type == "text") {
inputElements[i].value = "";
}
}
}

</script>

<!-- ---------- ELEMENT STYLING ---------- -->


<!-- See all of them here http://www.w3schools.com/jsref/dom_obj_style.asp -->
<div id="sampDiv">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget turpis eget quam luctus
malesuada ut ac nulla. Suspendisse fermentum magna neque, a auctor felis pretium eget.
Fusce ornare feugiat magna, ut faucibus sapien congue ut. Nunc nec fringilla ex, nec varius
nisl. Ut eget laoreet nisi. Aenean quis venenatis mauris, at volutpat ante. Donec sollicitudin
lacinia ornare. In quis accumsan ligula, id egestas enim.
</div>

<button id="chgBkColor">Background Color</button>


<button id="chgBkImg">Background Image</button>
<button id="chgBorderStyle">Border Style</button>
<button id="chgBorderWidth">Border Width</button>
<button id="chgBorderColor">Border Color</button>

<script type="text/javascript">

// Change background color


document.getElementById('chgBkColor').onclick = function(event) {
document.getElementById('sampDiv').style.backgroundColor = "#EFDECD";
}

// Change background image


document.getElementById('chgBkImg').onclick = function(event) {
document.getElementById('sampDiv').style.backgroundImage = "url('repeatBkgrnd.png')";
}

// Change border style


document.getElementById('chgBorderStyle').onclick = function(event) {
document.getElementById('sampDiv').style.borderStyle = "solid";
}

// Change border width


document.getElementById('chgBorderWidth').onclick = function(event) {
document.getElementById('sampDiv').style.borderWidth = "thick";
}

// Change border color


document.getElementById('chgBorderColor').onclick = function(event) {
document.getElementById('sampDiv').style.borderColor = "blue";
}
</script>

<!-- ---------- MANIPULATING THE DOM ---------- -->

<div id="sampDiv2"><p>Lorem ipsum dolor sit amet, <em>consectetur adipiscing</em> elit.


Proin eget turpis eget quam luctus malesuada ut ac nulla. Suspendisse fermentum magna
neque, a auctor felis pretium eget. Fusce ornare feugiat magna, ut faucibus sapien congue ut.
Nunc nec fringilla ex, nec varius nisl. Ut eget laoreet nisi. Aenean quis venenatis mauris, at
volutpat ante. Donec sollicitudin lacinia ornare. In quis accumsan ligula, id egestas
enim.</p><p>Lorem ipsum dolor sit amet, <b>consectetur adipiscing</b> elit. Proin eget
turpis eget quam luctus malesuada ut ac nulla. Suspendisse fermentum magna neque, a
auctor felis pretium eget. <em>Fusce ornare</em> feugiat magna, ut faucibus sapien congue
ut. <b>Nunc nec fringilla</b> ex, nec varius nisl.</p></div>

<img src="ntt-logo.png" id="logo2" alt="NTT Logo" height="180" width="180"><br />

<button id="goToGoogle">Go to Google</button><br />

<button id="forwardPage">Forward Page</button><br />

<button id="backPage">Back Page</button><br />

<button id="reload">Reload Page</button><br />

<script type="text/javascript">

// Get current web page info


document.write("Current URL : ", window.location.href, "<br />");
document.write("Current Host : ", window.location.hostname, "<br />");
document.write("Current Path : ", window.location.pathname, "<br />");

// Change site on button click


document.getElementById('goToGoogle').onclick = function(event) {
window.location.href = "http://google.com";
// OR
// window.location.assign("http://google.com");
}

// Go forward a page on click


document.getElementById('forwardPage').onclick = function(event) {
history.forward();
}

// Go back a page on click


document.getElementById('forwardPage').onclick = function(event) {
history.back();
}

// Use history.go(-2) or history.go(2) to jump multiple pages

// Reload page on button click


document.getElementById('reload').onclick = function(event) {
window.location.reload(true);
}

// You can get all ps and then target them like an array
var pElements = document.getElementsByTagName('p');
pElements[3].style.backgroundColor = "#EFDECD";

// Target the html


document.childNodes[1].style.backgroundColor = "#FAEBD7";

// Change the color of the 1st child in sampDiv2


var sampDiv2 = document.getElementById('sampDiv2');
sampDiv2.childNodes[0].style.backgroundColor = "#F0FFFF";

// Style the 1st child of sampDivs 1st child


sampDiv2.childNodes[0].childNodes[1].style.backgroundColor = "#BFAFB2";

// JavaScript can get confused by text nodes when targeting elements


// Text nodes are whitespace, which nodeType will identify with a 3
// while elements as a 1
// You can eliminate text nodes by deleting whitespace or by using a
// minimizer (lastChild and firstChild may not work)
document.write("Node Type : ", sampDiv2.childNodes[0].childNodes[0].nodeType, "<br />");

document.write("Node Name : ", sampDiv2.childNodes[0].childNodes[0].nodeName, "<br


/>");

sampDiv2.childNodes[1].childNodes[3].style.backgroundColor = "#BFAFB2";

// Changing element attributes


var nttLogo2 = document.getElementById('logo2');

// Check for attributes


document.write("Logo has alt : ", nttLogo2.hasAttribute("alt"), "<br />");

// Change attribute
nttLogo2.setAttribute("alt", "NTT Logo 2");

// Get attribute
document.write("Logo alt Value : ", nttLogo2.getAttribute("alt"), "<br />");

// Get all attributes and print them


var attribList = document.getElementById('logo2').attributes;

for(i = 0; i < attribList.length; i++){


document.write("Attribute ", i, " : ", attribList[i].nodeName, " : ", attribList[i].nodeValue,
"<br />");
}

// Add a p element after setting an attribute and text


var paragraph3 = document.createElement("p");

paragraph3.setAttribute("id", "paragraph3");

paragraph3.innerHTML = "Proin eget turpis eget quam luctus malesuada ut ac nulla.";

sampDiv2.appendChild(paragraph3);

// Insert the element before the 1st child


sampDiv2.insertBefore(paragraph3, sampDiv2.childNodes[0]);

</script>
<!-- ---------- OO JAVASCRIPT ---------- -->

<script type="text/javascript">

// Create a customer object by defining the attributes of John Smith


// The variable is a reference to the object in memory
var cust1 = {
name: "John Smith",
street: "123 Main",
city: "Pittsburgh",
state: "PA",
email: "jsmith@aol.com",
balance: 120.50,
payDownBal: function(amtPaid){
this.balance -= amtPaid;
},
addToBal: function(amtCharged){
this.balance += amtCharged;
}
};

// Retrieve the value for the object


document.write("Customer Name : ", cust1.name, "<br />");

// Change the value for the object


cust1.street = "215 Main St";
document.write("Customer Address : ", cust1.street, "<br />");

// Add a property to cust1


cust1.country = "US";
document.write("Customer Country : ", cust1.country, "<br />");

// Delete a property
delete cust1.country;

// Cycle through all the properties for the object


for (var prop in cust1) {
if (cust1.hasOwnProperty(prop)) {
document.write(prop, "<br />");
}
}

// Check if a property is in an object


document.write("name in cust1 : ", "name" in cust1, "<br />");

// Interact with an object using a function


function getInfo(cust){
return cust1.name + " lives at " + cust1.street + " in " + cust1.city + " " + cust1.state + "
email : " + cust1.email + " and has a balance of $" + cust1.balance;
}

document.write(getInfo(cust1), "<br />");


// Call object methods
cust1.payDownBal(20.50);
cust1.addToBal(10.00);

document.write(getInfo(cust1), "<br />");

// Create an object constructor


function Customer(name, street, city, state, email, balance){
this.name = name;
this.street = street;
this.city = city;
this.state = state;
this.email = email;
this.balance = balance;

this.payDownBal = function(amtPaid){
this.balance -= amtPaid;
};
this.addToBal = function(amtCharged){
this.balance += amtCharged;
};
}

var cust2 = new Customer("Sally Smith", "234 Main", "Pittsburgh", "PA",


"ssmith@aol.com", 0.00);

cust2.addToBal(15.50);

// Define a shared prototype property for all objects


Customer.prototype.isCreditAvail = true;

// We define prototype methods that are shared by every object created


Customer.prototype.toString = function(){
return this.name + " lives at " + this.street + " in " + this.city + " " + this.state + " email : "
+ this.email + " and has a balance of $" + this.balance.toFixed(2) + " Creditworthy : " +
this.isCreditAvail;
};

document.write(cust2.toString());

</script>

<!-- ---------- FORM VALIDATION ---------- -->

<div>
Enter your name:

<!-- When they leave the input send a reference to the input element, and a reference to the
hel error span -->
<input id="name" name="name" type="text" size="30" onblur="isTheFieldEmpty(this,
document.getElementById('name_help'))" />
<span id="name_help"></span>
<!-- this is the id number for the text box -->
</div>

<div>
Enter your street address:
<input id="street" name="street" type="text" size="30" onblur="isAddressOk(this,
document.getElementById('street_help'))" />
<span id="street_help"></span>
</div>

<div>
Enter your city:
<input id="city" name="city" type="text" size="30" onblur="isTheFieldEmpty(this,
document.getElementById('city_help'))" />
<span id="city_help"></span>
</div>

<div>
Enter your state code:
<input id="state" name="state" type="text" size="2" onblur="isStateOk(this,
document.getElementById('state_help'))" />
<span id="state_help"></span>
</div>

<div>
Enter your phone number:
<input id="phone" name="phone" type="text" size="15"
onblur="isPhoneOk(this, document.getElementById('phone_help'))" />
<span id="phone_help"></span>
</div>

<div>
Enter your email:
<input id="email" name="email" type="text" size="30" onblur="isEmailOk(this,
document.getElementById('email_help'))" />
<span id="email_help"></span>
</div>

<script type="text/javascript">

function editNodeText(regex, input, helpId, helpMessage)

{
// See if the info matches the regex that was defined
// If the wrong information was entered, warn them
if (!regex.test(input)) {

if (helpId != null)
// We need to show a warning
// Remove any warnings that may exist
while (helpId.childNodes[0]){
helpId.removeChild(helpId.childNodes[0]);
}

// Add new warning


helpId.appendChild(document.createTextNode(helpMessage));

} else {

// If the right information was entered, clear the help message


if (helpId != null){

// Remove any warnings that may exist


while (helpId.childNodes[0]){
helpId.removeChild(helpId.childNodes[0]);
}

}
}

// inputField – ID Number for the html text box


// helpId – ID Number for the child node I want to print a warning in
function isTheFieldEmpty(inputField, helpId) {

// See if the input value contains any text


return editNodeText(/^[A-Za-z\.\' \-]{1,15}\s?[A-Za-z\.\' \-]{1,15}\s?[A-Za-z\.\' \-]{1,15}/,
inputField.value, helpId, "Please enter a valid name.");
}

// inputField.value – Value typed in the html text box


function isAddressOk(inputField, helpId) {

return editNodeText(/^[A-Za-z0-9\.\' \-]{5,30}$/, inputField.value, helpId, "Enter a Street


(Ex.1234 Main St.)");
}

function isStateOk(inputField, helpId) {

return editNodeText(/^A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|
LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|
W[AIVY]$/, inputField.value, helpId, "Enter a State Code in Uppercase (Ex.NY, PA, CA)");
}

function isPhoneOk(inputField, helpId) {

return editNodeText(/^([0-9]( |-)?)?(\(?[0-9]{3}\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?[0-9]{4}|[a-zA-


Z0-9]{7})$/, inputField.value, helpId, "Enter a Phone Number (Ex.412-828-3000)");

function isEmailOk(inputField, helpId) {


return editNodeText(/^[A-Za-z0-9._-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/, inputField.value,
helpId, "Enter an Email (Ex. derekbanas@newthinktank.com)");

</script>

<!-- ---------- EXCEPTION HANDLING ---------- -->

<script type="text/javascript">
// Through exception handling we can catch and manage errors rather then
// crashing by surrounding problem code in a try block and handling it
// in a catch block

var custArray = ["Tom", "Bob", "Sally", "Sue"];

var getCust = function(index){


if(index > custArray.length){
throw new RangeError("Index must be >= 0 and <= " + custArray.length );
} else {
return custArray[index];
}
}

try {
document.write("Customer : ", getCust(5), "<br />");
}
catch(ex){
if (ex instanceof RangeError){
document.write(ex.message + "<br />");
}
}

</script>

</body>
</html>

object oriented java script

<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Object Oriented JavaScript</title>
</head>
<body>

<script type="text/javascript">
// A basic JavaScript object with properties and a method
var customer = {
name: 'Tom Smith',
speak: function(){

// this allows you to reference a specific objects value


// without knowing the objects name
return "My name is " + this.name;
},
// Objects can contain other objects
address: {
street: '123 Main St',
city: 'Pittsburgh',
state: 'PA'
}
};

document.write(customer.speak()+ "<br />");

// You access properties and object properties like this


document.write(customer.name + " lives at " + customer.address.street + "<br />");

// You can add properties


customer.address.country = "US";

document.write(customer.address.country + "<br />");

// Creating multiple objects of the same type with Constructor


// Functions. Constructors provide the functions that classes
// provide in other languages
function Person(name, street) {

// this allows us to refer to an object even though we


// don't know its name before it is created
this.name = name;
this.street = street;
this.info = function(){
return "My name is " + this.name + " and I live on " + this.street;
}
}

// You call constructor functions with new


var bobSmith = new Person("Bob Smith", "234 Main St");

document.write(bobSmith.info() + "<br />");

// instanceof tells you if an object is of a certain type


document.write("Bob is a person : " + (bobSmith instanceof Person) + "<br />");

// You can pass an object to a function and change values


function changeName(person){
person.name = "Sue Smith";
}
changeName(bobSmith);
document.write("Bob became " + bobSmith.name + "<br />");

// Objects are only equal if they reference the same object


var person1 = new Person("Paul", "123 Main");
var person2 = new Person("Paul", "123 Main");

document.write("Are they equal " + (person1 == person2) + "<br />");

// ---------- PROTOTYPE ----------


// Every function has a prototype property that contains an object
// You can add properties and methods to the prototype object
// and then when you call for them to execute they are used
// just as if they belonged to the object

function getSum(num1, num2){


return num1 + num2;
}

// Get the number of function arguments


document.write("Num of arguments : " + getSum.length + "<br />");

// You can add properties and methods to this object


function Mammal(name){
this.name = name;
this.getInfo = function(){
return "The mammals name is " + this.name;
}
}

// Use prototype to add a property


Mammal.prototype.sound = "Grrrrr";

// Use it to add a method


Mammal.prototype.makeSound = function() {
return this.name + " says " + this.sound;
};

var grover = new Mammal("Grover");

document.write(grover.makeSound() + "<br />");

// List all properties of an object


for( var prop in grover){
document.write(prop + " : " + grover[prop] + "<br />");
}

// Check which property belongs to prototype vs. the object grover


document.write("name Property of Grover : " + grover.hasOwnProperty("name") + "<br
/>");
document.write("sound Property of Grover : " + grover.hasOwnProperty("sound") + "<br
/>");

// You can add methods to built in JS objects


Array.prototype.inArray = function inArray(value){
for(i = 0; i < this.length; i++){
if(this[i] === value){
return true;
}
}
return false;
}

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

document.write("3 in array : " + sampArray.inArray(3) + "<br />");

// ---------- PRIVATE PROPERTIES ----------


// All properties in an object are public in that any function
// can modify or delete these properties.
// You can make properties private by declaring them as
// variables in a constructor

function SecretCode(){
// This value can't be accessed directly
var secretNum = 78;

// This function can access secretNum


this.guessNum = function(num){
if(num > 78){
return "Lower";
} else if(num < 78){
return "Higher";
} else {
return "You Guessed It";
}
}
}

var secret = new SecretCode();

// Returns undefined
document.write("Value of secretNum : " + secret.secretNum + "<br />");

document.write("Is 70 the number : " + secret.guessNum(70) + "<br />");

// Even if we add another function it can't access the secretNum


SecretCode.prototype.getSecret = function(){
return this.secretNum;
}
document.write("The secret number is " + secret.getSecret() + "<br />");

// ---------- GETTERS AND SETTERS ----------


// Getters and Setters can protect data, or provide useful
// ways to set its value
// I'll show you a bunch of getters and setters you may come
// in contact with
var address = {
street: "No Street",
city: "No City",
state: "No State",

// Provides styled data all at once


get getAddress() {
return this.street + ", " + this.city + ", " + this.state;
},

// Allows the user to set 3 values with 1


set setAddress (theAddress) {
var parts = theAddress.toString().split(", ");
this.street = parts[0] || '';
this.city = parts[1] || '';
this.state = parts[2] || '';
}
}

address.setAddress = "123 Main St, Pittsburgh, PA";


document.write("Address : " + address.getAddress + "<br />");
document.write("City : " + address.city + "<br />");

// ---------- CONSTRUCTOR GETTERS AND SETTERS ----------


// Still used even though it is (Deprecated)
function Coordinates(){
this.latitude = 0.0;
this.longitude = 0.0;
}

// Define the getter with the prototype to assign it to with


// the property name and the getter function
Object.__defineGetter__.call(Coordinates.prototype, "getCoords", function(){
return "Lat : " + this.latitude + " Long: " + this.longitude;
});

// Define the setter with the prototype to assign it to with


// the property name and the setter function
Object.__defineSetter__.call(Coordinates.prototype, "setCoords", function(coords){
var parts = coords.toString().split(", ");
this.latitude = parts[0] || '';
this.longitude = parts[1] || '';
});

var testCoords = new Coordinates();


testCoords.setCoords = "40.71, 74.00";

document.write("Coordinates : " + testCoords.getCoords + "<br />");

// ---------- GETTERS AND SETTERS WITH DEFINEPROPERTY ----------


function Point(){
this.xPos = 0;
this.yPos = 0;
}

// Use defineProperty to set getters and setters


// Pass the prototype to attach to along with the property name
// and define the functions to associate with get and set
Object.defineProperty(Point.prototype, "pointPos", {
get: function(){
return "X: " + this.xPos + " Y: " + this.yPos;
},
set: function(thePoint){
var parts = thePoint.toString().split(", ");
this.xPos = parts[0] || '';
this.yPos = parts[1] || '';
}
});

var aPoint = new Point();

aPoint.pointPos = "100, 200";

document.write("Point Position : " + aPoint.pointPos + "<br />");

// ---------- ECMASCRIPT 5.1 GETTERS AND SETTERS ----------

var Circle = function (radius) {


this._radius = radius;
};

Circle.prototype = {
set radius(radius) { this._radius = radius; },
get radius() { return this._radius; },
get area() { return Math.PI * (this._radius * this._radius); }
};
var circ = new Circle(10);

circ.radius = 15;

document.write("A circle with radius " + circ.radius + " has an area of " +
circ.area.toFixed(2) + "<br />");

// ---------- INHERITANCE ----------


// When we ask for a property if it isn't found in the main object
// then it is searched for in the prototype object. We are able
// to inherit methods and variables from any object in a
// chain of objects.

function Animal(){
this.name = "Animal";

// toString is a function in the main Object that every


// object inherits from
this.toString = function() {
return "My name is : " + this.name;
};
}

function Canine(){
this.name = "Canine";
}

function Wolf(){
this.name = "Wolf";
}

// Overwrite the prototype for Canine and Wolf


Canine.prototype = new Animal();
Wolf.prototype = new Canine();

// After you overwrite prototype its constructor points to the


// main object object so you have to reset the constructor after
Canine.prototype.constructor = Canine;
Wolf.prototype.constructor = Wolf;

var arcticWolf = new Wolf();

// Wolf inherits toString from Animal


document.write(arcticWolf.toString() + "<br />");

document.write("Wolf instance of Animal : " + (arcticWolf instanceof Animal) + "<br />");

// Properties added to any object in the chain is inherited


Animal.prototype.sound = "Grrrrr";

Animal.prototype.getSound = function(){
return this.name + " says " + this.sound;
}

Canine.prototype.sound = "Woof";
Wolf.prototype.sound = "Grrrr Wooof";

document.write(arcticWolf.getSound() + "<br />");

// More often then not it makes more sense to just inherit the
// prototype to speed up the lookup process
function Rodent(){
this.name = "Rodent";
}

function Rat(){
this.name = "Rat";
}

Rodent.prototype = new Animal();


Rat.prototype = Rodent.prototype;
Rodent.prototype.constructor = Rodent;
Rat.prototype.constructor = Rat;

var caneRat = new Rat();

// Wolf inherits toString from Animal


document.write(caneRat.toString() + "<br />");

// ---------- INTERMEDIATE FUNCTION INHERITANCE ----------


function extend(Child, Parent){
var Temp = function(){};

Temp.prototype = Parent.prototype;

Child.prototype = new Temp();

Child.prototype.constructor = Child;

function Deer(){
this.name = "Deer";
this.sound = "Snort";
}

extend(Deer, Animal);

var elk = new Deer();

document.write(elk.getSound() + "<br />");

// ---------- CALL PARENT METHODS ----------


function Vehicle(name) {
this.name = "Vehicle"
}

// Functions for the parent object


Vehicle.prototype = {
drive: function(){
return this.name + " drives forward";
},
stop: function(){
return this.name + " stops";
}
}

function Truck(name) {
this.name = name
}

// Inherit from Vehicle


Truck.prototype = new Vehicle();
Truck.prototype.constructor = Truck;

// Overwrite drive parent method


Truck.prototype.drive = function(){

// Call the parent method with apply so that the parent


// method can access the Trucks name value
var driveMsg = Vehicle.prototype.drive.apply(this);
return driveMsg += " through a field";
}

var jeep = new Truck("Jeep");

document.write(jeep.drive() + "<br />");

document.write(jeep.stop() + "<br />");

// ---------- SINGLETON PATTERN ----------


// Singletons are used when you only ever want 1 object to
// be created
// Let's say you want to create a game character with fixed
// stats
function Hero(name){

// Check if the object exists


if(typeof Hero.instance === 'object'){

// If it does return it
return Hero.instance;
}

// if it doesn't then create the hero


this.name = name;
Hero.instance = this;

return this;
}

var derekHero = new Hero("Derek");


document.write("Are hero is " + derekHero.name + "<br />");

// This won't change the name to Paul


var paulHero = new Hero("Paul");
document.write("Are hero is " + paulHero.name + "<br />");

// ---------- FACTORY PATTERN ----------


// The factory pattern can be used to generate different
// objects on request

function Sword(desc){
this.weaponType = "Sword";
this.metal = desc.metal || "Steel";
this.style = desc.style || "Longsword";
this.hasMagic = desc.hasMagic || false;
}

function Bow(desc){
this.weaponType = "Bow";
this.material = desc.material || "Wood";
this.style = desc.style || "Longbow";
this.hasMagic = desc.hasMagic || false;
}

function WeaponFactory(){};

WeaponFactory.prototype.makeWeapon = function(desc){
var weaponClass = null;

if(desc.weaponType === "Sword"){


weaponClass = Sword;
} else if (desc.weaponType === "Bow"){
weaponClass = Bow;
} else {
return false;
}

return new weaponClass(desc);

var myWeaponFact = new WeaponFactory();

var bladeFist = myWeaponFact.makeWeapon({


weaponType: "Sword",
metal: "Dark Iron",
style: "Scythe",
hasMagic: true
});

document.write(bladeFist.weaponType + " of type " + bladeFist.style + " crafted from " +


bladeFist.metal + "<br />");

// ---------- DECORATOR PATTERN ----------


// The decorator pattern allows you alter an object at run time
function Pizza(price){
this.price = price || 10;
}

Pizza.prototype.getPrice = function(){
return this.price;
}

function ExtraCheese(pizza){
var prevPrice = pizza.price;

pizza.price = prevPrice + 1;
}

var myPizza = new Pizza(10);

ExtraCheese(myPizza);

document.write("Cost of Pizza : $" + myPizza.price + "<br />");

// ---------- OBSERVER PATTERN ----------


// A single object notifies many objects (observers) when a
// state change occurs
var Observable = function() {
this.subscribers = [];
}

Observable.prototype = {
subscribe: function(subscriber) {
// Add the subscriber object to the list
this.subscribers.push(subscriber);
},
unsubscribe: function(unsubscriber) {

// Cycle through the subscriber array and delete


// the unsubscriber
for (i = 0; i < this.subscribers.length; i++) {
if (this.subscribers[i] === unsubscriber) {
this.subscribers.splice(i, 1);

// We assume it only subscribed once so we


// leave after it is found
return unsubscriber.name;
}
}
},
publish: function(data) {

// Cycle through all subscribers and send them the update


for (i = 0; i < this.subscribers.length; i++) {
this.subscribers[i].receiveData(data);
}
}
};

var OrganFanny = {
name: "Organ Fanny",
receiveData: function(data){
document.write(this.name + " received your info : " + data + "<br />");
}
}

var BoldmanYaks = {
name: "Boldman Yaks",
receiveData: function(data){
document.write(this.name + " received your info : " + data + "<br />");
}
}

// Add subscribers and alert them


observable = new Observable();
observable.subscribe(OrganFanny);
observable.subscribe(BoldmanYaks);
observable.publish('IBM at $145.30');

document.write(observable.unsubscribe(OrganFanny) + " Unsubscribed<br />");

observable.publish('IBM at $145.33');

</script>

</body>
</html>

You might also like