Created
February 1, 2019 16:38
-
-
Save amantheroot/6f45e7df4c791f8487db40df9c08dd71 to your computer and use it in GitHub Desktop.
Javascript cheat sheet by Derek Banas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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] = "[email protected]"; | |
// 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: "[email protected]", | |
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", "[email protected]", 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. [email protected])"); | |
} | |
</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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment