Simple Modal
http://www.ericmmartin.com/projects/simplemodal/

Segment.io -analytics platform
https://segment.io/

Raphael JS
http://raphaeljs.com/

HTML5 Canvas Tutorials
http://www.html5canvastutorials.com

Scroll Nav
http://scrollnav.com/

JS Graphs and Chart Libraries
http://socialcompare.com/en/comparison/javascript-graphs-and-charts-libraries

JavaScript InfoVis Toolkit
http://philogb.github.io/jit/demos.html

Flat UI
http://designmodo.github.io/Flat-UI/

Code Player
http://thecodeplayer.com/

Guidelines for Responsive Webdesign
http://coding.smashingmagazine.com/2011/01/12/guidelines-for-responsive-web-design/

Best Programming Quotations
http://www.linfo.org/q_programming.html

Rebuild YouTube’s mobile-like progress bar in jQuery
http://blog.ynh.io/2013/05/24/rebuild-youtubes-progress-bar.html#

Learn Knockoutjs
http://learn.knockoutjs.com/#/?tutorial=intro

lazy load
http://luis-almeida.github.io/unveil/
http://www.appelsiini.net/projects/lazyload

iScroll
http://cubiq.org/iscroll-4

CtrlAltDelete
http://www.ctrlaltdeletebook.com/

Navigation effect
http://labs.dragoninteractive.com/pufferfish.php

Charts
http://www.chartjs.org/?apo

Flipbook
http://inscopeapps.com/demos/flipbook/

Excel like editing in tables
http://warpech.github.com/jquery-handsontable/index.html

BonsaiJS – A lightweight graphics library with an intuitive graphics API and an SVG renderer.
http://demos.bonsaijs.org/

Animated Pie Chart: http://demos.bonsaijs.org/demos/pie/index.html
Pong:http://demos.bonsaijs.org/demos/pong/index.html

RaphaelJS – Another vector graphics library (check out the examples)
http://raphaeljs.com/

HammerJS – Easy implementation of multitouch events using JS
http://eightmedia.github.com/hammer.js/

SequenceJS – The Responsive Slider with Advanced CSS3 Transitions. Check out the slider with parallax effect
http://www.sequencejs.com/

JQuery Vector Maps – Jquery plugin that generates vector maps using SVG (and VML for older versions of IE)
http://jqvmap.com/

LetteringJS – Extreme control over font lettering
http://letteringjs.com/

CrossSlide – Very cool image slider with the famous Ken Burns effect.
http://tobia.github.com/CrossSlide/

Vanilla-JS – Tongue in cheek 0kb javascript library alternative to using other libraries
http://vanilla-js.com/

JQuery Plumb – Hooks elements together through visual elements and moves dynamically.
http://jsplumb.org/jquery/demo.html

JQuery Gantt Editor – Gantt Charts Using JQuery
http://roberto.open-lab.com/2012/08/24/jquery-gantt-editor/

JQuery Confirm Plugin – Clever way of doing inline confirmations
http://nadiana.com/jquery-confirm-plugin

BigScreen – Allows you to display content in full screen from the browser
http://brad.is/coding/BigScreen/

How to Load Javascript Asynchronously
http://css-tricks.com/thinking-async/

AngularJS in Action
http://goodfil.ms/blog/posts/2012/08/13/angularjs-and-the-goodfilms-mobile-site-part-1/

CSS & JQuery Clickable Maps
http://winstonwolf.pl/clickable-maps/united-states.html

Gauges in Javascript
http://www.justgage.com/

Introduction to Canvas
http://www.graphicmania.net/introduction-to-html5-canvas-with-java-script/

Websockets 101
http://lucumr.pocoo.org/2012/9/24/websockets-101/

Doodle Jump Game Remade using HTML5 – If you played the android/iphone version of this game, you’ll have fun with this:
http://cssdeck.com/labs/html5-doodle-jump/8

Improving Canvas Animation Performance
http://www.html5rocks.com/en/tutorials/canvas/performance/

Gameboy Color Emulator – Pure JS/HTML5 and works extremely well.
http://gamecenter.grantgalitz.org/

PlayCanvas – Forget what we all knew, 3D Games are definitely possible with HTML5 and have excellent performance.
http://playcanvas.com/demos/
http://playcanvas.com/a-multiplayer-3rd-person-shooter-in-html5/

Realistic Wristwatch – Animated wristwatch built using CSS/Javascript
http://codepen.io/TheSisb/pen/eAHyJ

10 Easy Steps to a Complete Understanding of SQL
http://tech.pro/tutorial/1555/10-easy-steps-to-a-complete-understanding-of-sql

Custom controls for HTML5 Video
http://blog.teamtreehouse.com/building-custom-controls-for-html5-videos

Kick ass resume:
http://www.rleonardi.com/interactive-resume/

CSS Zen Garden
http://www.csszengarden.com/?cssfile=/214/214.css&page=1

Laurence Gellert’s Blog
http://www.laurencegellert.com/

http://www.asymco.com/

http://ben-evans.com/

http://nsscreencast.com/

http://nshipster.com/

http://www.raywenderlich.com/

VARIABLES:
type name value

int highScore = 100;

NOTES:
-the value is optional at the time of declaration.
-type cannot be changed after definition.
–there’s something called dynamic typing but much more complex

int = integer variables: whole numbers with nothing after the decimal point

STRING LITERALS:
Strings are represented by values between double quotes with an @ sign at the front of the first double quote:
@”Hello, World!”

CONSTRUCTING STRINGS:
Create the message and put a placeholder in the middle of it.
@”There are %i in a year.”
-placeholders always begin with a percent sign
-after the % sign is whatever kind of data will go there.
In the above example, an i represents “integer”.

We follow the string with a comma and then the variable that we want to replace the placeholder with:
@”There are %i in a year.”, minutesInAYear

In the case of more than one variable:
@”There are %i in a %i day year.”, minutes, days

%i = integer
%f = floating-point variable
%c = single characters

NSLog(@”There are %i minutes in a year.”,minutesInAYear);
Traces out message in the console log.

CONDITIONAL CODE AND IF STATEMENTS
if (condition){
//code goes here
//…
}

Checking for equality in ObjC also uses “==”
A single equal sign after all is an assignment operation.

”!=” translates to “not equal”
“&&” = both
“||” = either or

SWITCH STATEMENT

int cateogry = 47;

switch (category){
case 40:
NSLog(@”It’s a category 40″);
break;
case 41:
NSLog(@”It’s a category 41″);
break;
case 42:
NSLog(@”It’s case 42″);
case 43:
case 44:
NSLog(@”It’s a category 42, 43, or 44″);
break;
default:
NSLog(@”I don’t know what it was!”);
break;
}

OPERATORS AND EXPRESSIONS
arithmetic operators:
+ – * /

score = score + 10
score +=10;
+= -+ *= /=

The above are “single operators”: there is no space between the characters

OPERATOR PRECEDENCE
result = 5 + 5 * 10;
multiplication and division take precedence….they go first and THEN addition and subtraction.

the above would look like this: 5 * 10 = 50 50 + 5 = 55. result = 55.

to impose order, put parenthesis:
result = (5 + 5) * 10;

COMPARISON
if (a == b) {..
if (a != b) {..
if (a > b) {..

if (a The value of a is 5 which is not what you expect.

TERNARY;
works on three things
condition ? true : false
//this whole operation will result in one single value. This will be evaluated and return something.
kind of like a mini if-else statement.

Example:

int playerOne;
int playerTwo;
int highScore;

if (playerOne>playerTwo){
highScore = playerOne;
}else{
highScore = playerTwo;
}

OR:
condition ? true : false
int highScore = (playerOne > playerTwo) ? playerOne : playerTwo;

LOOPS IN OBJECTIVE-C

WHILE Loop
int a = 1;
while (a < 10){
NSLog(@"The value of a is %i", a);
}

DO…WHILE Loop

int a= 1;
do{
NSLog(@"The value of a is %i", a);
a++;
} while (a<10);

FOR Loop

for ( int i = 1; i < 10; i++ ){
//do stuff
NSLog(@"The value of the index is %i", i);
//do stuff
//etc..
}

inserting the word "break" will break the whole cycle.
inserting the word "continue" will break just that iteration.

for ( int i = 1; i<5000; i++){
if ( i % 5 == 0) {
continue;
}
NSLog(@"The value of the index is %i", i);
}

//the above will check for every time the modulus of i and 5 returns 0 – in other words, every time i is divisible by 5, it continues;

FUNCTIONS

in Obj-c, you just give it a name. (no need to precede it with "function"

return type name parameters
int explodeSpaceship ( int x, int y ) {
NSLog(@"We're in the function");
//loops, if statements, anything!
//…
return 0;
}

function prototype – a description that the function exists, what it returns and what it exempts but nothing in the body.

DATA TYPES

Primitive types:
int
float
double
char
BOOL

12.5f //this is a float variable, f is a clue to the compiler that this is a float variable

BOOL iscompleted = YES
= NO

NSLog(@"The char is %i", isCompleted);
//YES ==1, NO == 0

ENUMERATIONS
enum seatPreference { window, aisle, middle };

enum seatPreference bobSeatPreference = aisle;
enum seatPreference fredSeatPreference = window;

-is a way of restricting ranges of values

enum seatPreference {window = 99, aisle = 199, middle = 399};

TYPEDEF
typedef – allows you to assign a new name to an existing data type
ex:
typedef int simonsInt;

typedef enum {window = 99, aisle = 199, middle = 399} seatPreference

PREPROCESSOR DIRECTIVES
#import //imports the code base
#define HIGHSCORE 100000 //sets the value and cannot be changed. Upper-case. can be accessed from elsewhere. declares things that need to be fixed.
ex: int a = HIGHSCORE + 500;
NSLog(@”%i”, HIGHSCORE);
#define PI 3.14159265

#if DEBUG
NSLog(@”the max value of an int is ….
#endif

DEFINING STRINGS
NOTE: there is no built-in string type in the Obj-C language.
NOTE: NSString is not officially part of the Obj-c language, it is part of the Foundation framework – a collection of pre-written pieces of code that we are linking to. (@import )

type name value
NSString *message = @”Hello”;
* is a pointer indication
all objects are accessed using pointers

I am making a variable called message and it is a pointer to an NSString.

NSString * message = @”Hello”;
NSLog(@”The value of message is %@”, message );

%@ is the placeholder for objects. A string is an object.

OBJECT ORIENTATION

Class: blueprint, definition, idea, description
-all classes describe two things: properties (attributes) and methods (behavior)
-one class can create multiple objects
Abstraction: idea of the focusing on core concepts of objects.
Encapsulation: keeping the functionality self-contained

NOTE: In objective-c, all objects are accessed using pointers.

MESSAGES AND METHODS:
Other OO languages call methods this way: myObject.someMethod();

ObjC does this [myObject someMethod];

result = [myObject someMethod];

to pass in argument:
[myObject someMethod:arg];

multiple args:
[myObject insertString:@”Hello” atIndex:11];

[myObject someMethod: [anotherObject anotherMethod]];

USING EXISTING CLASSES IN THE FOUNDATION FRAMEWORK

NSString *message = @”Hello”;
NSString *message2 = [message uppercaseString];

NSLog(@”The result is %@”, message2);

NSDate *myDate = [NSDate date];
NSLog(@”The date is %@”, myDate);

within class reference documentation there are + signs and – signs.
+ signs are class methods
– signs are instance methods

Automatic Reference Counting (ARC)

MEMORY MANAGEMENT:
core skill for obj-c developer
garbage collection cannot be used on the iPhone, iPad or the MacOS X versions prior to Leopard

use reference counting

an object is created and a area of memory is cleaned for that object. That object gets a retainCount. (A number)

MyClass &myObj = [MyClass];
[myObj someMethod0; //etc.
[myObj release]; //retain count is set to 0 and Obj C destroys it.

retainMessage: another object sets the retain count to 2

If you own the object , you must release it.
You own an object if you created it, copied it or retained it:
alloc
new
copy
retain

If you don’t own the object, you must not release it.

OBJECT CREATION
most common way:
Class *myObj = [[Class alloc] init];
Person *fred = [[Person alloc] init];
Dog *fido = [[Dog alloc] init];
Customer *acmeCorp =[[Customer alloc] init];
NSAutoRleasePool * pool = [[NSAutoReleasePool alloc] init];

if you have written any code that uses alloc or init, you own that object.

USING AUTORELEASE POOLS

anyClass *myObj = [[AnyClass alloc] init];
Person *fred = [Person new];
[myObject retain];
NSString *newMessage = [oldmessage copy];

When to use autorelease:
Auto-release means release it later.
[fred autorelease];
gets added to an autorelease pool
[pool drain]

NOTE: when you write a method that creates and returns an object, that is called a Factory method.

createEmployee{
//create a new object
Employee *fred = [[Employee alloc] init];
[fred autorelease];
return fred;
}

NARC (new alloc retain copy) if these words are in the object creation, you own it. You must call release.

if it is NOT, you do NOT own it and you must NOT call release.

With the creation of Automatic Reference Counting (ARC), you no longer have to handle any releases.
What ARC manages:
it is not a garbage collection
runs at compile time
predictable

Rules of Automatic Reference Counting
1. don’t call memory management methods
no retain
no release
no autorelease
no retainCount
no dealloc (deallocation)

2. don’t use NSAAutoReleasePool
NSAutoReleasePool is replaced by @autoreleasepool blocks

http://blogs.sitepointstatic.com/examples/tech/css3-starwars/index.html

http://raphaeljs.com/

CSS – Cascading Style Sheets

CSS rule has two main parts: a selector and one or more declarations

h1 = selector
{color:blue; font-size: 12px;} = declaration

color = property
blue = value

The selector is normally the HTML element I want to style.

CSS allows you to specify our own selectors called “id” and “class”

ID selector is used to specify a style for single, unique element.
-ID selector uses the id attribute of the HTML element and is defined with a “#”.
-do not start an ID name with a number. Will not work in Firefox

Class selector is used to specify a style for a group of elements. The class selector is most often used on several elements
-the class selector uses the HTML class attribute, and is defined with a “.”
-do not start a class name with a number. This is only supported in IE.

Cascading order:
1. browser default
2. external style sheet
3. internal style sheet (in head section)
4. inline style (inside an HTML element)

STYLING

Background –

“background-color” -specifies the background color of an element
-color is most often specified by
-a HEX value – “#ff0000”
-an RGB value like “rgb(255,0,0, 0)” (the fourth digit is the alpha)
-color name – red

“background-image” -specifies an image to use as the background of an element
-background-image:url(‘image_tree.png’);

“background-repeat” -by default, the image is repeated so it covers the entire element.
-by default, the background image property repeats an image both horizontally and vertically.
-can be set like so: background-repeat: repeat-x; or background-repeat: repeat-y;

“background-position” – position of the image is specified by this property
-background-position: right top;

TOPICS CRITICAL FOR ONLINE VIDEO -last updated April 19, 2012

_____________________________________________________________________________________________

1.) MARKET SHARE OF BROWSERS & DEVICES
-Combined data from desktop and mobile yields that roughly 74% of the market now supports HTML5.

-Since IE6/7/8 do not support HTML5, alternatives like Flash remain very useful for video playback

-Both Chrome & Firefox surpassed IE 6/7/8’s combined market share

Mobile:
-iOS and Android still lead by a wide margin -both support HTML5 video.

-Android at large still supports Flash
-Android 4.0 (Ice Cream Sandwich) is not always released with built-in Flash support
-not on Samsung’s Galaxy S2.

In order to play audio (AAC/MP3) and video (MP4/FLV) in Adobe Flash, the following two statements must be true:
– browser must have the Adobe Flash plugin installed
– version of Adobe Flash must be at least 9.0.115

For playing HTML5 video, the following statements must be true:
– browser must support the HTML5 video tag
– browser must support the files that are embedded in the tag.

_____________________________________________________________________________________________

2.) MEDIA FORMATS

-one of the biggest challenges with HTML5 video is the fragmented support for audio/video formats

-on desktop, split is almost exactly 50/50 –
– Chrome/Firefox/Opera supporting WebM
– Chrome/IE/Safari supporting MP4

Both iOS and Android only support MP4 video.

_____________________________________________________________________________________________

3.) TAG ATTRIBUTES
– 90% of tag attributes are supported
– HTML5 video tag supports several attributes

Most important: poster, preload, autoplay and controls.

Poster:
– image that is displayed before playback of the video starts.
– should always be displayed before playback, regardless of the preload attribute.
– the video tag should contain the poster to its display area -black borders will show if the poster has a different aspect ratio.
– for audio files, the poster image should stay visible all times, since there is no video frames to display.

Preload:
– mobile browsers ignore “preload” as videos are never preloaded

Autoplay:
– mobile browsers ignore “autopsy” as videos are never played upon page load

IE ignores the preload = none attribute.
-the implication here is that IE9 loads a part of your MP4 upon each pageview, instead of waiting until a user actually starts the video.
-this may add to a substantial increase in streaming costs

Mobile browsers ignore preload (video is never preloaded) and autoplay (video is never played upon page load)

_____________________________________________________________________________________________

4.) JavaScript API

80% of API features work reliably.

In addition to its HTML attributes, the video tag provides an extensive JS API for controlling its content.

Common use cases for this are the rendering of custom controls (JW Player) or page interaction with the video timeline (Popcorn.js)

Popcorn.js allows video, audio and other media to control elements of a webpage.
Popcorn.js utilizes the native HTMLMediaElement properties, methods and events.

Scripting has been found to be reliable and consistent across the various desktop browsers.

On mobile, both iOS & Android ignore getting or setting the volume as those two use the hardware to control the volume.
Apple blocks the scripted play().

_____________________________________________________________________________________________
5.) FULLSCREEN PLAYBACK

50% fullscreen support is halfway there

Although the HTML5 fullscreen specification is still in its infancy, most browsers have now implemented either a fullscreen control or a scripting API.

both the iPad and Android tablets support a fullscreen control, but no API yet. Both always play video in fullscreen, so control is not needed.

HTML – mark up language, content
CSS – style sheet language, presentation
JS – programming language, behavior
JS -is intentionally limited, only works inside another application -the web browser.

web browser contains a web page and the page contains JS
can’t access local files.
can’t access database
cant access hardware

was designed to manipulate web pages.
is a client-side language used to add interactivity to web pages.
is sent to the client
JS can be disabled.
Is not Java, is not a light version of Java. has nothing to do with Java.
standardized is actually called ECMAScript
the standard now used is ECMAScript 3 (adopted in 1999)

JS is platform agnostic
Firebug allows you to directly run JS in the browser.
JS is case-sensitive

is an interpreted language. Does not need be to compiled.

//——————————————————-//

each JS statement ends with a semi-colon
one statement per line
JS is whitespace insensitive.
JS runs/reads code line by line.
Position of JS in the page does matter b/c it will be executed as soon as the browser sees it.

alert(“Hello”); ==

myscript.js contains this code: alert(“Hello”);

HTML5 does not require that the attribute type be set. Browser will automatically assume is JS

Good rule of thumb to have your JS in your body tag at the very bottom.
CSS should be loaded in the head section

//——————————————————-//
variable is a container

var year;
var custEmail;
var foo;

can be made with letters, number, _ and $.
(Cannot start with a number.)

Technically, the word var is not required. but highly recommended.

when creating multiple vars, you can put it one line:

var year, month, day;
or
var year = 2011, month = 10, day = 31;

JS is a weakly typed language.
in JS, you can use double quotes or single quotes.

= assignment
== equality
=== strict equality

if ( a == b) {…
if ( a != b){…
if ( a === b){…
if ( a!== b){…
if (a>b){…

if (aplayerTwo) ? playerOne : playerTwo;

//——————————————————-//

console.log(“foo”);

log can be changed to one of four other words.

debug – not much different from log
info -the letter i
warn – yellow
error – red

//——————————————————-//

for loops:

while – runs while condition is true;
do – runs through code at least once;
break; – breaks out of the for loop if condition is met;
continue; – stops that particular iteration and returns to condition again.

//——————————————————-//
functions:

best practice to define functions before calling.

//——————————————————-//
Arrays

array is a single variable that holds multiple values

var multVar = [ ];

accessible by index
multVar[2] = 50;

var multVal = new Array(); //arrays are objects.

var multVal = Array();

all JavaScript arrays are dynamic.

arrays have properties and methods.

multVal.length(); //returns number of objects in that array

method is a function that belongs to an object.
someObject.someMethod(); //to call a method

var multVal = [20,30,40,50];
var reversedVal = multVal.reverse();
.join();
.sort();

EX:
var arrayOfLinks = document.getElementsByTagName(“a”);
//returns every link in that DOM

//——————————————————-//
Numbers

All JS numbers re 64-bit floating point numbers.

addition vs concatenation

var foo = 5;
var bar = 5;

console.log(foo + bar); //10

var foo = ‘5’;
var bar = ‘5’;

console.log(foo + bar); //55

var foo = 5;
var bar = ‘5’;

console.log(foo + bar); //10
(if any part of the vars in the equation is a string, it will treat the whole operation as a string.

var foo = 5;
var bar = “b”;

console.log(foo * bar); //NaN (Not a number)

If something is not a number but needs to be:
var foo = “55”; //could be “abc”
var myNumber = Number (foo); //makes it number

if we need to know something is not a number:

if (isNaN(myNumber)) {
console.log(“It’s not a number!”);
}

OR //a double-negative

if (!isNaN(myNumber)) {
console.log(“It’s IS a number!”);
}

//——————————————————-//
Math Object

var x = 200.6;
var y = Math.round(x); // 201

var a = 200, b = 10000, c = 4;
var biggest = Math.max(a,b,c);
console.log( biggest); //10000

var smallest = Math.min(a,b,c);
console.log(smallest); //4

//——————————————————-//
Strings
double quotes and single quotes work. Don’t mix the quotes.

if quotes are needed inside of a string, use escape to tell JS that these are not intended to close the string.

var phrase = “He said \”that’s fine,\” and left.”;

String methods

var phrase = “I know JavaScript”;

phrase.toUpperCase();
phrase.toLowerCase();

var words = phrase.split(” “);
var position = phrase.indexOf(“know”);

var segment = phrase.slice(6,5);

var str1 = “Hello”;
var str2 = “hello”;

//——————————————————-//
Dates
var today = new Date(); //with no parameters passed, returns a date and time

var y2k = new Date(2000, 0, 1);
//year, month, day

var y2k = new Date(2000,0,1,0,0,0);
//year, month, day, hours, minutes, seconds

var today = new Date();

today.getMonth(); // returns 0 -11
today.getFullYear(); //YYYY (Not zero-based)
today.getYear(); //deprecated
today.getDate(); //1 – 31 day of month
today.getDay(); //0-6 day of week. 0== sunday
today.getHours(); //0-23
today.getTime(); //milliseconds since 1/1/1970

today.setMonth(5);
today.setFullYear(2012);
today.setDay(0);

comparing dates – note that dates are objects.

var date1 = new Date(2000,0,1);
var date2 = new Date(2000,0,1);

if (date1 == date2) {… //false!

if(date1.getTime() == date2.getTime()) { …//true!

//——————————————————-//
Objects in JS

objects have properties that are variables outside of that object.

Can be set this way:
var player = new Object();
player.name = “Fred”;
player.score = 1000;
player.rank = 1;

OR

var player1 = {name:”Fred”, score:10000, rank:1};
var player2 = {name:”Sam”, score:1000000, rank:5};

function playerDetails(){
//display info
console.log(this.name + ” has a rank of: ” +
this.rank + ” and a score of ” +this.score);
}

player1.logDetails = playerDetails;
player2.logDetails = playerDetails;

player1.logDetails();//Fred has a rank of: 1 and a score of 10000
player2.logDetails(); //Sam has a rank of: 5 and a score of 1000000

//——————————————————-//
DOM – Document Object Model

Document means the page.
Object -everything that makes up the document. h1, p, a, body
Model – describes the relationship between all of the objects. – a set of terms or standards use.

web page, pieces, agreed upon set of terms.

//——————————————————-//

DOM thinks of the web page in terms of nodes

One node per tag
ex: elements, attributes, text, comments and so on.

Node Types:
Node.ELEMENT_NODE == 1
Node. ATTRIBUTE_NODE == 2
Node.TEXT_NODE == 3

Accessing DOM elements:
when going after an element in a DOM, the first question to ask is this element unique? does it have an unique id?

class can be added to any number of elements
id can (and should) only be used once

document.getElementById(“someId”);

var myElement = document.getElementById(“someId”);
//creates a handle right into that element.

document.getElementsByTagName(“a”);
var myListItems = document.getElementsByTagName(“li”);

once an object is created, the methods can be reused to search within those objects.
ex.

var myListItems = document.getElementsByTagName(“li”);
var myLinks = myListItems.getElementsByTagName(“a”);

myElement.getAttribute(“align”); //name of attribute in quotes

myElement.setAttribute(“align”, “left”); // name in quotes, value in quotes

//——————————————————-//
Creating DOM elements
1. create the element.
2. append child

var myNewElmt = document.createElement(“li”);
myElment.appendChild(myNewElmt);

var myTxt = document.createTextNode(“lorem ipsum”); OR
newTxt.innerHTML = “lorem ipsum”;

//——————————————————-//
Events
(all lowercase)
onload
onclick
onmouseover
onblur
onfocus

eventHandler or eventListener

Method 1: inline HTML

Method 2: name of element, dot notation and name of event:
myelement.onclick = function(){ // code…};
//this is an anonymous function -does not have a name

Method 3:
addEventListener
huge benefit is you can add several handlers for one event.

document.addEventListener(‘click’, myFunction, false);
document.addEventListener(‘click’, anotherFunction, false);
document.addEventListener(‘click’, aThirdFunction, false);

IE prior to IE9 does not have addEventListener.

cross-broswer add event helper method

function addCrossBrowserEventListener(elementName, eventName,functionName){
//does the addEventListener function exist?
if(elementName.addEventListener){
//yes-use it
elementName.addEventListener(eventName, functionName, false);
return true;
}else[
//otherwise use attachEvent
elementName.attachEvent(“on”+eventName, functionName);
return true;
}
}

//——————————————————-//
onClick and onLoad Events

window.onload = function (){….//

window object represents a full browser window
it’s the top-level object in JS
contains the document object
only write this window.onload function ONCE per page
if you have several multiple javascript files linking, and they all have the window.onload function, the last one is going to win.

//——————————————————-//
onBlur and onFocus
onFocus occurs when you click on a form field or tab into it.
onBlur occurs when you leave that form field or tab out of it

var emailField = document.getElementById(“email”);

emailField.onfocus = function() {
if ( emailField.value == “your email”) {
emailField.value = “”;
}
};

emailField.onblur = function() {
if ( emailField.value == “”) {
emailField.value = “your email”;
}
};

//——————————————————-//
Timers

four methods:
setTimeout to perform a single action after a delay
setInterval to repeat it after that delay and to keep repeating

clearTimeout
clearInterval

setTimeout(function, delay);
setTimeout(callMessage, 5000);

//————————-example———————-//
Change an image
var myImage = document.getElementById(“mainImage”);

var imageArray = [“_images/overlook.jpg”,”_images/winery_sign.jpg”,”_images/lunch.jpg”,
“_images/bigSur.jpg”,”_images/flag_photo.jpg”,”_images/mission_look.jpg”];
var imageIndex = 0;

function changeImage() {
myImage.setAttribute(“src”,imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}

// setInterval is also in milliseconds
setInterval(changeImage,5000);

OR
var intervalHandle = setInterval(changeImage,5000);
myImage.onclick = function (){
clearInterval(intervalHandle);
}

//——————————————————-//
Common problems to be aware of

syntax errors – closing bracket, closing parenthesis, etc.

calling a function that doesn’t exist

typos in the DOM methods – case sensitivity.
-getElementById (correct) vs. getElementByID (incorrect)

undefined variables by window not being completely loaded yet.

assignment instead of equality
a = b (assignment) vs. a == b (equality)

NaN (Not a number)

//——————————————————-//
Using Firebug
HTML tab
DOM tab

will give you the more up-to-date version of content that is displayed, for instance, if JavaScript changes content, Firebug will show you the updated content whereas the View Source tool will show you the original

//——————————————————-//
building smarter forms

document.forms.frmContact

//———————–txtfield———————//

property:
myTextField.value

events:
onfocus –
onblur – always called when you leave the field.
onchange
onkeypress
onkeydown
onkeyup

//—————–checkboxes/radio buttons:————//

property:
myCheckBox. checked (true or false)

events:
onclick
onchange

//———————–select list:——————-//
properties:
mySelect.type (select-one or select-multiple)

select-one:
mySelect.selectedIndex

select-multiple:
mySelect.options[x].selected (true or false)

events:
onchange

//———————–submit btn——————-//
main event:
onsubmit

by subscribing to the onsubmit event, we can interrupt the call to the server and perform a check on the information. If it is not formatted correctly, return false;

function prepareEventHandlers() {
document.getElementById(“frmContact”).onsubmit = function() {
// prevent a form from submitting if no email.
if (document.getElementById(“email”).value == “”) {
document.getElementById(“errorMessage”).innerHTML = “Please provide at least an email address!”;
// to STOP the form from submitting
return false;
} else {
// reset and allow the form to submit
document.getElementById(“errorMessage”).innerHTML = “”;
return true;
}
};
}

//——————-hiding and showing content—————//

// show and hide sections of a form
function preparePage() {
document.getElementById(“brochures”).onclick = function() {
if (document.getElementById(“brochures”).checked) {
// use CSS style to show it
document.getElementById(“tourSelection”).style.display = “block”;
} else {
// hide the div
document.getElementById(“tourSelection”).style.display = “none”;
}
};
// now hide it on the initial page load.
document.getElementById(“tourSelection”).style.display = “none”;
}

NOTE: by initially setting it to show the content, you’re ensuring full functionality of page regardless of whether or not JavaScript is enabled.

//——————-hiding and showing content—————//
setting inline styles

element.style.anyCSSStyleProperty.property….
myElement.style.color = “red”;

style properties that use hyphens in CSS become cameCase in JavaScript – remove the dash and any subsequent word becomes capitalized.

setting properties in JavaScript…you set as string.
myElement.style.swidth = “230px”;
myElement.style.color = “#fff”‘;

setting the class:
myElement.className = “someCSSClass”;
to clear it:
myElement.className = “”;

document.getElementById(“mainContent”).className = “exampleClass”;