JavaScript Coding Notes

JavaScript:

JavaScript is case sensitive.

Put it in external .js file or at end of body element.

Link to a JavaScript file:
<script src=”js/myJavaScript.js”></stript>

link to JavaScript file:
<script src=”directory/javascriptFile.js”></script>
or put JavaScript in source:
<script>
</script>
Comments:
/* */

Can’t use quotes inside of quotes. Escape or use single quotes:

document.write()
<body>
<script>
document.write(“My Name is \”Will\”");
or
document.write(‘My Name is ‘”Will’”);
</script>

 

alert() & confirm()

alert: creates a popup window:
<script>
alert(‘Woah! Hello!’);
</script>

confirm(): Gives an option: OK or Cancel on popup window:

<script>
confirm(“Do you want to leave?”);
</script>

Tells person after they click which one they clicked:
<script>
var c = confirm(“OK or Cancel?”);
if( c) {
alert(“You pressed \”OK\”");
} else {
alert(‘You clicked “Cancel”‘);
}
</script>

Prompt (asks a question):
text, default value
text = question
default value = default answer

<script>
prompt(“How old are you?”, “Doesn’t matter”);
</script>
This is useless unless we can harvest information:

<script>
var p = prompt(“How old are you?”, “”);
if( p) {
alert(p + ” is your age”);
} else {

alert (“No input was typed”);
}
</script>
Variables:
Possible changing value.

var Varname = “VALUE” ;

Must start with a letter, an underscore or a $. Can not start with alert. Can not contain spaces.

var $Name = “My Name”;

var Name2 = “My Name”;

var Number = 23;

var Number =23.5;
var Number = “23″;

Invalid:
var 2Name
var #Name
Global variable: declared outside of a function and can be accessed from inside a function and is not destroyed when function finished running.

Local: created inside a function and can not be accessed from outside a function and they are destroyed when function stops running.

Conjugation:
Conjugate using the + sign.

<script>
var Name = “Will”;
var Age = ” and I am 22 years old!”;
document.write(“My name is ” + Name + age);
</script>

<script>
var Anything = “anything”;
document.write(“anything is” + Anything);
</script>

Math: Arithmetic
Addition: + Subtraction: – Multiplication: * Division /
<script>
var myAge = 22;
var Nextyear = 1;
Total = myAge + nextYear;
document.write(“Next year I will be ” + Total + ” yearls old!”);
</script>

Modulus:
remainder from a devision:
Use % to return remainder or mod. 10 % 3 would be 1 because the remanded when 10 is divided by 3 is 1.
<script>
var Ten = 10;
var Mod = Ten % 3;
alert(Mod);
</script>
Increment:
++ used to increment up by 1.
<script>
var Age = 22;
Age++; //++ is the same as: var Age = 22+1;
Age++; // 24
alert(age);
</script>

Decrement:
– moves down 1.

<script>
var Year = 2012;
Year–; //year is 2011//
alert(Year);
</script>

Putting it all together:

<script>
var p = prompt(“How old are you right now?”, “”);
if( p) {
p++; // increments var p making it 1 higher for alert//
alert(“You will be ” + p + ” next year!”);
} else {
alert (“sorry, you didn’t put a number in”);
}
</script>

Window Location Lecture 104
With window.location we can change the location of the current page. We can direct or redirect traffic to anywhere we like.

<script>
window.location = “http://google.com/”;
</script>
<script>
window.location = “home.php”;
</script>
<script>
window.location = “home.html”;
</script>

window.open :

window.open(p1, p2, p3, p4)
URL (page you want to open), name (like target attribute in html, blank, self, top, parent, frame), options (how you want window to be open: width, height, left, top, scrollbar, resizable, location, menubar (hides or shows menubar)), replace (replace will replace your current page with a new one) – all params are optional:

window.open(p1, p2, p3, p4)
framename

 

Empty Link: Can use as an event trigger such as onclick on onmousedown to activate a function.

<a href=”#”>Link</a>
<a href=”javascript: void(0);”>Empty link</a>

String manipulation: 106
string:
A variable that contains letters. Like a sentence:
integer: whole number, negative or positive
float:
number with a decimal: 1.3, -1.5

variable.length;

<script>
var Alphabet = “abcdefghijklmno”; //string
var Age = 22; // integer
var ExactAge = 22.89; //float
document.wirte(Alphabet.length + ” ” + Age.length + ” ” + ExactAge.length);
//age.length and exactAge.length won’t work because they aren’t strings. Would need to add quotes.”
</script>

variable.toUpperCase() //changes all letters to upper case
and .toLowerCase //changes all letters to lower case
<script>
var Food = “Triple Patty King Burger”;
document.write(Food.toUpperCase());
</script>

<script>
var Pangram = “The Quick Brown Fox Jumps Over the Lazy Dog”;
document.write(Pangram.toLowerCase());
</script>

<script>
var p = prompt (“What is the password?”, “”);
if(p.toLowerCase()==”password” && p.length==8) {
alert(“Access granted!”)
} else {
alert(p.toUpperCase() + ” is wrong!”);
}
</script>
Comparison Operators:
return true or false

var v = 10;
v > 10; // returns false
v == 10; returns true

== equals
!= is not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to

<script>
var Number == 20;
if (Number == 20) { alert(“number is equal to 20″);
</script>

<script>
var Breathing = 0; // 0 means false, 1 means true
if(!Breathing) {
alert(“Not breathing!”);
}
</script>

//would return not breathing, because breathing = 0 (false)

&& (and) means all comparisons have to be true:
|| (or)
<script>
var Age = 18;
var Name = “Sam”;
if (Age>=18 && Name==”Sam”) {
document.write(“Age is equal to 18 or Name is Sam”);
}
</script>

if Statements
<script>
var color = “blue”;
if(color==”blue”) {
// My code here //
}
</script>

<script>
var Year = 2013;
if(Year==2013)
{
//If Year is exactly “2013″ – this is true.
// TRUE
}
</script>

<script>
var Year = 2013;
var Car = “Audi”;
if(Year==2013 && Car==”Audi”) {
//Ture
//Execute code
}

if(Year==2013 && Car==”Benz”)
{
//False
}

if(Year!=2012 || Car==”Lambo”) {
//True
}
</script>
If Else Statements:
only lower case letters for if: if

<script>
var FavCar = “Audi”;
if(FavCar==”Benz”)
{
alert(“My favorite car is Mercedes”);
}
else
{
alert(“My favorite car is Audi”);
}
</script>

Else If:
has to go in order: if, else if, else. only 1 if, else, but unlimited else if.

<script>
var Name = “Will”;
if(Name==”Andrew”)
{
var FutureAlert = “Hello, Andrew”;
}
else if(Name==”Will”)
{
var FutureAlert = “Welcome, Will!”;
}
else
{
var FutureAlert = “Hey there, guest user!”;
}
alert(FutureAlert); //code to execute can go here to apply to all//
</script>

Switch statements:
// We use switch(variable) to switch comparison. We use case x to change the case. Works just like if / else if but use switch / case to look through for a match.

<script>
var age = 22;
switch(age)
{
case x1:

break;
case x2:

break;
default:

break;
}
</script>

<script>
var Name = “Will”;
switch(Name) {
case “Mike”:
alert(“Your name is Bob!”);
break;
case “Billy”:
alert(“Your name is Billy!”);
break;
case “Will”:
alert(“DING! This is what we want!”);
break;
default:
alert(“the Name Variable does not match anything above”);
break;
}
alert(m);
</script>

Functions:

<script>
function Name(parameter1, parameter 2) //defines function name and parameters. Paramaters are local variables to the function.
{
alert(“My name is NOT Frank Zappa”);
// what the function does goes in here. Parameter 1 and 2 can be inserted in here
}
Name(//put in values for parameters); //calls the function
</script>

 

<script>
function Name(name1, name2)
{
alert(name1 + ” is the first name\n” +
name2 + ” is the second name”);
}
Name(“Will”, “Student”);
</script>

Both parameters must be defined. If you only have one, do this:

<script>
function Name(name1, name2)
{
if(name1==undefined || name2==undefined)
{
var message = “Missing one parameter”;
}
else
{
var message = name1 + ” is the first name\n” +
name2 + ” is the second name”;
}
alert(message);
}
Name(“Will”);
</script>

\n sends to new line.
The word undefined without quotes is javaScript value for nothing.
Return:
<script>
function AddThis(x,y) {
var total = x + y;
return total;
}
//alert() the total: Alerts “3″
alert(AddThis(1,2));
</script>
<script>
function AddThis(x,y) {
var total = x + y;
return total;
}
//alert() the total: Alerts “3″
alert(AddThis(1,2));
//document.write() the total: Will write “3″
document.write(AddThis(1,2));

//put the total in a variable:
//Does nothing.
//var T = 4;
var T = AddThis(1,3);
</script>

Boolean value: yes or no, true or false, 1 or 0.

return; Return runs function and defines the result but doesn’t spit anything out the user can see. anything below return line javascript ignores. You need to use document.write() to add the value returned to the page or alert or prompt to spit the value out to the user in a popup window

<script>
function NameOrAge(type, value)
{
type = type.toLowerCase();
if(type==”age”)
{
return value + value; //addition arithmetic; doubles age
}
else if(type==”name”)
{
var newString = “Your name is ” + name;
return newString;
}
else
{
return “Type did not match \”age\” or \”name\”";
}
}
alert(NameOrAge(“age”, 22));
// could also do alert(NameOrAge(“name”, “Will”));
// alert(NameOrAge(“anything else”, “some value”)); for different results
</script>

Events:
onClick, onDBLClick, onFocus, onBlur, onMouseDown, onMouseUp, onMouseMove, onMouseOut, onMouseOver, onKeyDown, onKeyPress, and onKeyUp.

onclick: makes something clickable to call a function:
<button type=’button’ onclick=’function();’>Button</button>

<script>
function Name()
{
alert(“Will”);
}
</script>

<span onclick=’Name()’>Click Me</span> (as a span doesn’t change how mouse looks when hover over)

onDblClick: on double click:
<script>
function DblClick(txt)
{
alert(txt);
}
</script>
</head>

<body>
<button type =’button’ onDblClick=’DblClick(“My custom text!”)’>Button Name</button>

onFocus:
When a web page has a text field, and you or another use clicks the field to start typing they are focusing on the text field. So you can run a function on the click of a text field with onFocus. Here’s an example:

<script>
function StartFocus()
{
alert(“You are focused”);
}
</script>
</head>

<body>
<input type=’text’ onfocus=’StartFocus();’ value=” />
onBlur
Can run a function when someone clicks out of a field:

<script>
function StartBlur()
{
alert(“You are leaving the field\nBlurred!”);
}
</script>
</head>

<body>
<input type=’text’ onblur=’StartBlur();’ value=” />

onMouseOver:
runs function when you scroll over an element:

<script>
function MouseOver()
{
alert(“My mouse is over this element!”);
}
</script>

<body>
<div onMouseOver=’MouseOver();’>
Mouse over me!
</div>

<div onMouseOut=”">&nbsp;</div>

onMouseOut: works the same as onMouseOver but runs when your mouse leaves area.

onMouseDown:
When you click mouse down but before you release.
<a href=’javascript: void(0);’ onMouseDown=’javascript: prompt(“Mouse down!”‘>
onMouseUp:
Same as onMouseDown, but when you release mouse. onClick = onMouseDown + onMouseUp.

onMouseMove

<script>
function MoveMe()
{
alert(“Moved”);
}
</script>
</head>
<body>
<div onmousemove=”MoveMe();’>
Put the mouse in here and move it
</div>
Keyboard Events:

onKeyPress
This is like onClick. This is the full action of pressing and releasing keyboard key to run function.

<script>
function AfterPress()
{
alert(“Pressed key”);
}
</script>
</head>

<body>
<input type=’text’ onKeyPress=’AfterPress();’ placeholder=’Type in me’ />
</body>

onKeyDown:
like on mouse down but with key press

onKeyUp:
like on mouse up but with key press

 
getElementById()
Get property by html element to change their values:
document.getElementById()
put it at the bottom of the page right before closing body tag.

//grabs items from elements with ID MyID:

<body>
<input type=’text’ id=’MyID’ value=’Value’ />
<script>
var MyID = document.getElementById(“MyID”);
MyID.value = “JS put this value in here”;
</script>
</body>

To change the value of something we add .value.

<div id=’test’>Change me</div>
<script>
documet.getElementById(‘test’).innerHTML = “<b>New HTML in here!</b>”:
</script>

CSS: background-color: red;
JS: document.getElementByID(‘MyID’).style.backgroundColor = “red”;

<div id=’myDiv’ // This part gets written in here from JavaScript Below: style=’background-color: red;’// onclick=’changeBG();’>
Change to red
</div>
<script>
function changeBG() {
document.getElementById(‘myDiv’).style.backgroundColor = “red”;
}
</script>

//disable button and put border on text:

<div id=’TestID’>Change this</div>
<button type=’button’ id=’Button’ onclick=’ChangeMe();’>Click2Change</button>

<script>
function $(id) {
return document.getElementById(id);
}

function ChangeMe() {
document.getElementById(‘TestID’).style.border = “1px solid red”; // Can also be written as $(‘TestID’).style.border = “1px solid red”; //
$(‘TestID’).innerHTML = “Added a border and this text!”;
$(‘Button’).value = “Changed!”; //should be .innerHTML for button rather than .value.
$(‘Button’).disabled = true;
}
</script>
escaping:
use a \ before character
var Car = “My favorite car is “Audi”";

What browser sees
var Car = “My favorite car is” ERROR

solution:
var Car =”My favorite car is \”Audi\”";

Can use escape(str) to escape longer strings:

<script>
var EscapeMe = “The cow jumped over the moon!?”;
document.write(escape(EscapeMe));
</script>

Displays:
The%20cow%20jumped%20over%20the%20moon%21%3F

UnescapeMe
<script>
var UnescapeMe = “The%20cow%20jumped%20over%20the%20moon%21%3F”;
document.write(unescape(UnescapeMe));
</script>

Arrays:

//define array:
var MyArray = new Array();

//add to array:
MyArray[0] = “Bob”;
MyArray[1] = “Bill”;
MyArray[2] = “Joe”;

document.write(MyArray[0] + ” and ” + MyArray[2] + ” are friends”);

//Format
Variable[Number] = value;

Condensed Array:
//Can write them all on one line:

var MyArray = new Array(“Bob”, “Bill”, “Joe”);
var MyArray = ["Bob", "Bill", "Joe"];
alert(MyArray[2]);

Multi-dimenstional arrays:
// several groups of arrays [0][0] to call first value from first group. [1][0] to call first value from second group

//99 would be a single array mixed with multi array.
var MultiArr = [["Bob", "Bill", "Joe"], [22, 32, 42], 99];
alert(MultiArr[0][2]);
alert(MultiArr[0][2] + ” is ” + MultiArr[1][2]);

The ["Bob", "Bill", "Joe"] is
MultiArr[0][0]
MultiArr[0][1]
MultiArr[0][2]

The [22, 32, 42] is
MultiArr[1][0]
MultiArr[1][1]
MultiArr[1][2]
The 99 is
MultiArr[2]
for loops 116

The first type of loop we will cover has 3 sections.
The counter variable. This keeps track of how many times the code has executed this code.
The condition. Keep looping until the condition is met.
The counter variable increment. Usually +1.

for(i = 0; i < 5; i++)
{
document.write(“Looped ” + i + ” times <br />”);
}

for(variable in array)
{
//code to run
}

Example:

var MyArray = new Array(“Audi”, “BMW”, “Benz”);

for (v in MyArray)
{
document.write(v + “<br />”);
}
for (v in MyArray)
{
document.write(MyArray[v] + “<br />”);
//v will run 0, 1, 2 and run Audi, BMW, Benz
}

Displays
0
1
2
Audi
BMW
Benz

while loops:
tell code to run while a condition is met
while(variable < endingCondition) {
// your code
}

var myNumber = 0;
while(myNumber < 3) {
document.write(myNumber);
myNumber = myNumber + 1;
}

do while loops:
executes code then checks if condition is met and decides if it should run again.

var i=0;
do {
document.write(i + ” is the int. number <br />);
i++;
}
while(i < 3);

Breaking out of loops:

for(i=1; i< 10; i++) {
document.write(i + ” is the current number”);
if(i==5) {
break;
}
}

//runs until hits 99. Without num++ would run an infinite loop.
var num = 0;
while(num < 99) {
alert(num);
if (num==0) {
break;
}
num++;
}

How you could include feeds from multiple friends in same feed:

var friendFeed = new Array(“Feed 1″, “Feed 2″, “Feed 3″);
for(index in friendFeed) {
document.write(friendFeed[index] + ” <hr />”;
if(index==1) {
break;
}
}

Skipping a loop cycle:
use continue; statement
for(i = 1; i <= 5; i++) {
if(i==3) {
continue;
}
document.write(“The number is ” + i + “<br />”);
}

var myString = “The quick brown fox jumps over the lazy dog”;
var iAmSplit = myString.split(” “);
document.write(“Here is the array: <br />”);
for(index in iAmSplit) {
document.write(iAmSplit[index] + “, “);
}

 

 
split()
splits string into an array with each character as a value.
split has 2 parameters. The first value is the separator which determines which character separates the string values. The second is the limit which is the number of maximum splits in an array.

You can split a string by a certain value through what’s in-between ().
for instance split(” “); could be used to split a sentence into an array index separated by each space between words. split(“”); would give every character a spot in the array. split(); would make the whole array a string.
var myString = “The quick brown fox jumps over the lazy dog”;
var iAmSplit = myString.split(” “);
document.write(“Here is the array: <br />”);
for(index in iAmSplit) {
document.write(iAmSplit[index] + “, “);
}
substr()
lets you extract parts of a string through character position. every letter number and space takes up one position.

starting character and length to extract are parameters. starting character is mandatory. length to extract is optional. if not set it extorts the whole thing.
//would start at the 7th character and remove everything else. Would display nothing is better than this website.
var myString = “I love this website!”;
document.write(“Nothing is better than ” + myString.substr(7));
try Catch

try section has the code that will run if there are no errors.

catch section has the code that will run if there was an error in the try section.

try
{
allert(“This is typed wrong!”);
}
catch(e)
{
e = “This error occurred: \n” + e
alert(e);
}

<button type=”button” class=”button” onclick=”try()”;>Run</button>

Throw
lets you create an exception in try catch.

var Name = prompt(“Enter your name:”);
try
{
var leng = Name.length; //Length of user input
if(leng > 5) {
throw “Long Name”;
} else if (leg < 5) {
throw “Short Name”;
} else {
throw “5 letter name”;
}
}
catch(e)
{
alert(e);
}
date
var d = new Date();
document.write(d);
//returns full date and time: Mon Jul 15 2014 09:39:48 GMT-0600
var d = new Date();
document.write(d.getDay());

//returns array number for day (0 for sunday, etc)

var d = new Date();
var day = d.getDay();
var WeekDays = new Array(“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”);

document.write(WeekDays[day[);

//returns day of week: sunday, etc.

var d = new Date().get ///Date(),Date(),FullYear();
getDate(); //19
getDay(); //0-6
getFullYear(); //2013
getTimezoneOffset(); //Offset from GMT to your time
getTime(); //miliseconds from Jan 1 1970 to now.
getMonth(); //0-11
getSeconds(); //seconds past the minute 0-59
getMinutes(); //minutes past the hour 0-59
getHours(); //returns hour on users computer 0-23

Math
rounding
round()
var RoundMe = 1.5509416;
document.getElementById("demo1").innerHTML = Math.round(RoundMe);

exponents
(number, power);
var Exponent = Math.pow(2, 5);
alert(Exponent);
// 2*2*2*2*2

pi
Pi is an object, not a method. it pulls information and doesn't have an action based on it. It pulls in Pi.
var p = Math.PI;
document.getElementByID("demo2").innerHTML = p;

Ceiling
//rounds up to the next whole number
var myNumber=13.212;
document.getElementById("demo3").innerHTML = Math.ceil(myNumber);
Floor
//rounds down to the nearest whole number
var myNumber=13.212;
document.getElementById("demo3").innerHTML = Math.floor(myNumber);
Min & Max
min() max()
document.getElementById("demo5").innerHTML = Math.min(1, 5, 8, 0.5, 6) + "<br />";
///would return 0.5 (smallest number)
document.getElementById("demo5").innerHTML = Math.max(1, 5, 8, 0.5, 6) + "<br />";
// would return 99 (largest number)

Advanced:
cos(x) Returns the cosine of x
tan(x) tangent
sin(x) sine
log(x) natural logarithm
sqrt(x) square root

BEDMAS
Brackets
Exponents
Division/Multiplication
Addition/Subtraction
Is the order in which Math works. So if you want to add some number together thn divide, use brackets, etc.

// the 2 would square the answer:
var Answer = Math.pow((19 + 1)*5, 2);
alert(Answer);
Regular Expressions:
how to define:
var MyRegExp = new RegExp(pattern, modifiers);

or it can be written like:
var MyRegExp = /pattern/modifiers

Where the pattern goes inside the slashes followed by your modifiers.

A modifier is a specific rule the pattern should stick to. Like being case-sensitive or to be global. Modifiers can also be called "flags".

When you use brackets in any RegExp, you are looking for a specific range of characters.

[abc] Will find any character between the brackets. So it will look for a, b or c.
[^xyz] Will find any character NOT in the brackets. So it will look for the whole alphabet until the letter x.
[0-9] Will look for any number from 0 to 9.
[A-Z] Will find any letter in the alphabet that is uppercase.
[a-z] Will find any letter that is lowercase.
[A-z] Finds anything from a capital A to a lowercase z.
(box|floor|bed|desk) Finds any of the 4 words. The | (pipe) means OR like how || means or).
youWord Looks for “youWord” exactly. Case sensitive.

here’s an example of how to use
var myExp = /Will/g; //g is global modifier
var test = myExp.test(“My name is Will”);
alert(test);
//returns true because it finds Will.
Quantifier / What it does
//Letter isn’t important and are variables. We are looking at symbols:

g* Matches a string that has zero or more occurrences of g
t? Matches a string that has zero or one occurrences of t. Doesn’t stop at 1 like * does.
z+ Matches a string that has at lease one z. So, one or more.
a{X,} Matches any string that has “a” at least X amount of times in a row.
b{X,Y} Matches any string that has “b” at least X to Y amount of times. ie: b{2,3} matches “bb” and “bbb”
c{X} Matches any string that has X amount of occurrences in a row.
^w Matches a string that starts with “w”
q$ Matches a string that ends with “q”

var myExp = /l{2}/g;
var test = myExp.test(“My name is Will”);
alert(test);

//looks for 2 ls. returns true because Will has 2 ls.
Metacharacters
. Looks for a single character except for newlines
\w Looks for a word character
\W Looks for a non-word character
\d Looks for a digit
\D Looks for a non digit character
\s Looks for a whitespace character
\S Looks for a non-whitespace character
\b Looks for a match at the beginning/end of a word
\B Looks for a match not at the beginning/end of a word
\0 (Zero) Looks for a NUL character
\n Looks for a new line character
\f Looks for a form feed character
\r Looks for a carriage return character
\t Looks for a tab character
\v Looks for a vertical tab character.

var myExp = /Will\n/g;
var test = myExp.test(“My name is Will\n test”);
alert(“New \n Line”);

// would alert the below because it found Will\n for new line.
New
Line

Modifiers are how we modify our pattern.
i = case Insensitive. Or.. “Ignore-case”.
g = global. It will find all matches and not stop at just one.

We add modifiers at the end of a pattern.

var myRegExp = /JS/gi;
//searches for JS and ignores case.
alert(myRegExp.test(“This is a js class”));
//returns true

Testing and Using:

.test()
If you want to test if your RegExp works, you can do what the example above has been doing. They use the .test() method.

youRegExp.test(“your string”);

.test() will give you “true or “false” answers. True if there is at least one match. False if there is no match.

.replace()

If you want to replace a pattern with a string, you can use .replace() object.

string.replace(“string or RegExp”, “replacement”);

var myRegExp = /sentence/gi;
var str = “Change this sentence”;
document.getElementById(“demo6″0.innerHTML = str.replace(myRegExp, “string”);
.match()

We can also get all the matches into an array by using the .match() method.
//need to set g (global modifier) to get more than one value. always set g with match.

var myRegExp = /string/g;
var str = “This is my test string”.match(myRegExp);
for(v in str) {
alert(str[v]);
}

// to get all matches

var myRegExp = /string/g;
var str = “This is my test string string”.match(myRegExp);
var matches = str.length;
alert(matches)

// would alert 2

.match() will return all its results into an array. Our array was var str. If the global modifier (g) is not set then your array will only have one value. Thats the first value the pattern runs into.

Navigator:
tells you information about visitor:

Object
platform the platform the user is on ie: Win32
cookieEnabled true/false True means cookies are enabled.
onLine true/false True if browser is online (This is always true if you are accessing the website)
userAgent the agent that is sent to the server from your browser.
appName the name of your browser ie: Netscape // Netscape makes Mozilla
appVersion the version of your browser
appCodeName the alias name of your browser. ie: Mozilla

var NavigatorInfo = “appCodeName: ” + navigator.appCodeName + “<br />”;
NavigatorInfo += “appName (Browser Name): ” + navigator.appName + “<br />”;
NavigatorInfo += “appVersion: ” + navigator.appVersion + “<br />”;
NavigatorInfo += “cookieEnabled: ” + navigator.cookieEnabled + “<br />”;
NavigatorInfo += “platform: ” + navigator.platform + “<br />”;
NavigatorInfo += “userAgent: ” + navigator.userAgent + “<br />”;
NavigatorInfo += “onLine: ” + navigator.onLine;

var demo = document.getElementById(“demo0″);
demo.innerHTML = NavigatorInfo;

setInterval 126
runs code more than once at every set time we specify.
setInterval()
function, millisecond delay
function is the code we want to run.
millisecond delay is how long we “wait” between each interval. 1000 = 1 second.

function time() {
var d = new Date();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
//code below puts a 0 in front of minutes fewer than 10 in counter
if(minute<10) {
minute = “0″ + minute;
}
var str = hour + “:” + minute + “:” + second;
document.getElementById(“demo0″).innerHTML = str;
}
var initiate = setInterval(function(){time()}, 1000);
//1000 milliseconds == 1 second

//need to clear interval to stop
clearInterval(initiate); //to stop code from running

setTimeout()
runs code once after specified delay time.

var delayedAlert = setTimeout(function(){alert(“Delayed!”);}, 5000);

Always put setInterval and setTimeout into a variable. The function parameter should have no spaces for older browsers

objects:
Creating our own objects. They are similar to arrays in that they can hold multiple values and arrays:

Example object:
.length Date().getDay(); // Date() is an object and .getDay(); is an attached method.

var MyWallet = {
cards:
{
visa: 1,
mastercard: 1,
amex: 0,
debit: 1
},

id: “yes”
}
alert(MyWallet.id); //would alert yes
alert(MyWallet.cards.visa); //would alert 1
alert(MyWallet.cards); //would alert objectObject to show it is array with multiple values. Case sensitive

MyWallet.cards.visa = 1
is the same as
MyWallet['cards']['visa'] = 1;

Can use objects or arrays. arrays can only hold value where objects can hold more. They both have pros and cons.