#Javascript Notes
###Core Concepts -
- HTMl is the markup language - CONTENT ON PAGES
- CSS is the style sheet language - PRESENTATION ON PAGES
- JAVASCRIPT is the programming language - BEHAVIOR ON PAGES
Javascript is a programming language. Often times javascript is referred to as a scripting language, but most programmers dismiss this and argue javascript is a programming language.
You cannot write a desktop application with javascript. Javascript only works within another application, IE web browser.
- Javascript cant access local files - Security risk.
- Cant directly access Database
- Cant access Hardware (USB, ETC)
Javascript was designed to manipulate web pages
Javascript is a client-side language. It is sent from the server to their browser and rendered client side.
Server side would be PHP, ASP.NET, Ruby on Rails
*Javascript has popped up in Adobe Acrobat/ Photoshop
- Javascript has also popped up in server-side
- Node.js
- Google Apps Script
#####Javascript is NOT JAVA. Nothing to do with it.
Javascript is interpreted, not compiled. Javascript IS CASE SENSITIVE
Grouped into statements; Seperate instructions or commands to say peice by peice what you want to do. ex.
- pixels to the left
- make a menu option disappear or appear
- alert message
#####Javascript is whitespace insensitive!
Add comments by // comment goes here....
Execution order - Javascript goes from the top, one by one.
Javascript is executed as it lies in the DOM.
###Creating variables
Variables are a container (No spaces, made of letters, numbers, underscore, dollar sign, no numbers first)
var variablename; (representing the variable)
var customerEmail;
var todaysDate;
Define and Set:
var year;
year = 2011;
Or Define and Set:
var year = 2011;
Variable names are case sensitive
var x = 200;
Javascript is a weakly typed language. Don't need to specify which type of variable you're trying to set.
myVariable = 200; (integer)
myVariable = "hello"; (doubled quotes)
myVariable = 'hello'; (can use single quotes, treated the same)
myVariable = true; (boolean)
myVariable = false; (boolean)
Javascript does care what type of variable it is, but any javascript variable can hold any of these values, even arrays and functions.
The point of making variable is to be able to use the variable.
if ( condition ) {
//code goes here
//What happens if variable is true
}
- parenthesis ()
- brackets []
- braces {}
Not interchangable. Need to be in pairs. If theres an open, needs to close.
if ( b > 20 ) {
}
To check equality in javascript use == considered a single operator
Javascript has another way of checking equality ===
Never use single = sign to check a value. Single = is to set a value.
Checking not equal to use !=
Several statements surrounded by curly braces are called a code block
.
Code blocks can be nested.
var amount = 500;
if ( amount < 1000 ) {
alert("It's Less Than 1000!");
} else {
if ( ) {
//code goes here...
}
}
###Operators and Expressions
Arithmetic operators = + - * %
used along with = (assignment operator)
result = a + b;
score = score + 10;
score += 10; (same as above, shorthand)
+= -= *= %= Operator Precidence (some operator symbols are regarded as more important than other... Same as math.)
result = 5 + 5 * 10;
Multiplication first then addition
result = ( 5 + 5 ) * 10;
result = 100
###Comparison Operators:
if ( a == b )
var a = 5;
var b = 10;
if ( a = b ) {
//always true!
//Make sure you use the correct operator for equality... DOUBLE EQUALS SIGN. this single equals command will set a = 10 and a will always equal b, so it will always be true, even when you don't want it to be true... (common mistake, difficult to debug)
}
One equals = ASSIGNMENT TWO equals == EQUALITY Three equals === STRICT EQUALITY
var a = 5;
var b = "5";
if ( a == b ) {
alert("Yes, they're equal");
}
else {
alert("They are NOT equal");
}
If you were to use a === (strict equal) on the above, it needs to be the same data type as well as being the same data. As you can see above, var a is an integer, while var b is a string. Different data types, so it would not be considered true with ===, but would be considered true with ==
###Sending Messages to the console
Messages in the console =>
console.log
console.info
console.debug
console.warn
console.error
Same error, with different icon. Most of the time you will use console.log
var foo = 10;
var bar = 20;
if ( foo < bar ) {
console.log("foo is less than bar");
console.log("and here's a second message");
console.log("and here's the third message");
}
###Working with loops
Loops are also reffered to as iterations.
#####WHILE LOOP
var a = 1;
while ( a < 10 ) {
console.log(a);
a++;
}
#####DO...WHILE LOOP
var a = 1;
do {
console.log(a);
a++;
} while ( a < 10 );
Do while will always run at least once, because the loop runs before the condition is checked.
while loops are MUCH more common than do...while loops.
var i = 1;
while ( i < 10 ) {
// do stuff
// do stuff
i++;
}
- Setup the index variable
- Check the condition of the variable
- Increment the index
#####FOR LOOP
Bring those 3 into the condition of the loop..
for ( var i = 1 ; i < 10 ; i++ ) {
//do stuff
//do stuff
//do stuff
}
Occasional Vocab
#####Break - Jump us out of the loop.
for ( var i = 1 ; i < 5000 ; i++ ) {
//do stuff
//do stuff
if (i == 101) {
break;
}
//do stuff
}
break jumps out of the loop If you say break, it manually stops running the loop.
#####Continue -
for ( var i = 1 ; i < 5000 ; i++ ) {
//do stuff
//do stuff
if (i % 5 == 0) {
continue;
}
//do second set of stuff
//do second set of stuff
}
At some point, if it hits the word continue, it means to jump back up and check the condition again. Not carry on to second stuff.
###CREATING FUNCTIONS
As we start to add more code we want to make sure it doesnt get messy and hard to read. So as with all languages we want to break apart large amount to smaller reusable modular peices.
All we are doing is taking several statements, wrapping them up and giving them a name. These are called functions.
function myFunction () {
console.log("We're in the function");
// loops, if statements, anything!
// ...
}
sometime later, you call myFunction
myFunction();
if it's in a function, it won't run unless you call it.
Youll end up having a lot of functions. Doesnt matter where you put these in the file, because the javascript engine will scan the code to see if they exist, before it tries to run anything.
BEST PRACTICE TO DEFINE FUNCTION BEFORE YOU CALL THEM!!!!!!
Functions with parameters -
function myFunction ( x,y ) {
var myVar = x * y;
console.log(myVar);
}
Same rules as variables.
function myFunction ( x,y ) {
var myVar = x * y;
console.log(myVar);
// we can return values
return myVar;
}
square brackets indicates dealing with arrays. Javascript uses zero poistion index. First position is always zero
var singleValue;
singleValue = 99;
var multipleValues = [];
multipleValues[0] = 50;
multipleValues[1] = 60;
multipleValues[2] = "Mouse";
console.log(multipleValues[2]);
creating shorthand arrays.
var multipleValues = [ 50,60,"Mouse" ]; //automatically places 0 1 2 positioning to array...
longhand
var multipleValues = new Array();
arrays are objects...
var multipleValues = Array();
all are the same... all arrays are dynamic.
because arrays are objects they have properties that we can get to about them.
var multipleValues = [10,20,30,40,50];
console.log(multipleValues.length);
- length of array is 5
- highest index is [4]
- This is because [0] is the first index
#####Array Methods
someFunction(params); // to call a function
methods are functions that belong to an object
someObject.someMethod(); // to call a method
var multipleValues = [10,20,30,40,50];
//built in methods to javascript
.reverse();
.join();
.sort();
console.log( reverseValues.join() );
arrays are everywhere...
var myArrayOfLinks = document.getElementsByTagName("a");
###WORKING WITH NUMBERS!!!
var x = 200;
//numeric literal
//JavaScript numbers are 64-bit floating point numbers.
x = 200.5;
var foo = 5;
var bar = 5;
console.log(foo + bar); //10
var foo = "5";
var bar = "5";
console.log(foo + bar); //55
the plus sign is going to concatenate them because it thinks you want to treat these as a string.
var foo = 5;
var bar = "5";
console.log(foo + bar); //55 = one is a string
var foo = 5;
var bar = "b";
console.log(foo * bar); //NaN
NaN means DOES NOT MAKE SENSE!
var foo = "55"; //could be "abc"
var myNumber = Number(foo); // make it a number!
if ( isNaN(myNumber) ) {
console.log("It's not a number!");
}
isNaN returns either true of false. Be careful here. You're asking if Not A Number is true, so
var foo = "abc";
var myNumber = Number(foo);
if ( isNaN(myNumber) ) {
console.log("It's not a number!");
}
It would return true to it NOT being a number.
If you want to return true to it being a number, you use a double negative, as no isNumber is built into javascript.
ex) double negative - if NOT NOT a number by using !
if ( !isNaN(myNumber) ) {
console.log("It 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);
var smallest = Math.min(a,b,c);
ex. Math.PI Math.random() Math.sqrt() Math.log()
###WORKING WITH STRINGS
var myString = "Double Quotes Work.";
var myString = 'Single Quotes Work';
var myString = 'One or the other.";
#####Quotes inside quotes
var phrase = "Don't mix your quotes.";
Good! var phrase = 'Don't mix your quotes.'; No Good! Apostrophe Acts as a quote...
var phrase = "He said "that's fine," and left.";
No Good! Mixing Double Quotes With single quotes...
You need to surround with backslash if you want to use quotes within a quotes!
var phrase = "He said \"that's fine,\" and left.";
This tells javascript the quotes inside the quotes are supposed to be the closing quote.
###String Properties
var phrase = "This is a simple phrase.";
console.log(phrase.length); // 24
strings can be treated as arrays
var phrase = "This is a simple phrase.";
console.log( phrase.toUpperCase()); //THIS IS A SIMPLE PHRASE.
Strings can be treated as METHODS.
var phrase = "This is a simple phrase.";
var words = phrase.split(" ");
splits this string at the space.
Not always split at the space, but if a comma seperated list for ex.
var words = phrase.split(",");
would split into array at the comma.
var phrase = "We want a groovy keyword.";
var position = phrase.indexOf("groovy");
would return index position of the word groovy. we is 0 want is [1] a is [2] groovy is [3]
If term is not found with indexOf it returns -1...
if ( phrase.indexOf("DDDD") == -1) {
console.log("That word does not occur.");
}
index of finds the first occurance of that phrase in the string.
There is also if ( phrase.lastIndexOf(" ")) { //code goes here.... } This is used to get the last occurance of that phrase in the string.
var phrase = "Yet another phrase.";
012345678901
var segment = phrase.slice(6,11);
this will count 6 positions into the variable...Grab characters from 6 - 11 (5 characters) as an array of characters. this value will be returned into the new variable named segment Contrary to what you may think, this does no change the original string, it creates a copy.
other string methods
.substring(start,end)
.substr(start,length)
var str1 = "Hello";
var str2 = "hello";
str1 != str2
To make equal to, make either both upper or both lower case...
if ( str1.toLowerCase() == str2.toLowerCase() {
console.log("Yes, equal");
}
if ( str1.toUpperCase() == str2.toUpperCase() {
console.log("Yes, equal");
}
#####REMEMBER JAVASCRIPT IS CASE SENSITIVE!!!!! var str1 = "aardvark"; var str2 = "beluga"; if (str1 < str2) { ... //true
var str1 = "aardvark";
var str2 = "Beluga";
if (str1 < str2 ) { ... //false!
ABCD less than abcd...
###WORKING WITH DATES!!!
var today = new Date();
Current date and time
var y2k = new Date(2000,0,1); //year, month, day
month is zero based
var y2k = new Date(2000,0,1,0,0,0);
here are getMethods for time!
var today = new Date();
today.getMonth(); // returns 0-11
today.getFullYear(); //YYYY (not zero-based)
today.getDate(); // 1-31 day of month
today.getDay(); //0-6 day of week, with 0 == sunday
today.getHours(); //0-23
today.getTime(); // milliseconds since 1/1/1970
var myDate = new Date(1906,11,9);
console.log( "Grace Hopper was born on: ", myDate.getDay() );
here are setMethods for time! var today = new Date();
today.setMonth(5);
today.setFullYear(2012);
today.setDay(0);
etc
Comparing Dates
var date1 = new Date(2000,0,1);
var date2 = new Date(2000,0,1);
if ( date1 == date2 ) { ... //false!
Javascript compares them and realizes they are two seperate objects, so it views them as two seperate dates.
###Working With Objects
Object - Self contained peices Examples: array, date, DOM, making our own
Container that gathers together some data and some behavior and give them a name
var playerName = "Fred";
var playerScore = 10000;
var playerRank = 1;
These are similar variables we want grouped. In order to group them, we need to place them inside of a container.
var player = new Object();
This creates a generic object container and calls it player. Then we just decide what we want the interal peices of this object to be.
var player = new Object();
player.Name = "Fred";
player.Score = 10000;
player.Rank = 1;
Outside of an object = variable Inside of an object = Properties
Shorthand for creating an object
Create two objects
var player1 = { name: "Fred", score: 10000, rank: 1 };
var player2 = { name: "Sam", score: 10000000, rank: 1 };
If you know that this function is going to be associated with different objects, what I can use is the word this to refer to the current one. So whatever object it is, I am going to go into its name/score or rank property.
function playerDetails() {
//Display information about each player
console.log(this.name + " has a rank of: " +
this.rank + " and a score of " + this.score);
}
Create logDetails as a method of the objects created ; making logDetails up right now just to associate with player1 and player2 object. Now both of these objects have a method called logDetails. If we call it, it will reach through and call the playerDetails function.
player1.logDetails = playerDetails;
player2.logDetails = playerDetails;
Finally call the logDetails function of player1 or player2 to run the function and receive something from the console.log
player1.logDetails();
player2.logDetails();
###What is the DOM - Document Object Model
Knowing your way around the DOM = Most important tool for a javascript developer.
#####What is the document? For us, the document means the page/webpage. Not the website, the webpage.
#####What is the object? An object is just a thing. Dates are objects, arrays are objects. Any thing that makes sense to treat as an individual thing. The elements, the components, the individual peices.
#####What is the model? What they mean is a model as in a business model, or data model. With a webpage, we should be able to take any html and represent it as a tree structure. We could even decide on words for the peices of the tree, like nodes. We can even describe relationships between nodes, like parents of certain nodes, and child of nodes The model ends up being an agreed upon set of terms.
#####What do we end up with? The document object model is an agreed upon set of terms that describe exactly how to interact with peices of a webpage. Its not a language. Its an idea. Its a convention. But javascript agrees on this DOM, so its available in javascript. Its an agreed upon terminology that will allow us to describe and interact with any webpage.
###Working with nodes and elements
Different tags are viewed as different nodes
DOM documentation - The different types of nodes
Node.ELEMENT_NODE == 1
Node.ATTRIBUTE_NODE == 2
Node.TEXT_NODE == 3
Node.CDATA_SECTION_NODE == 4
Node.ENTITY_REFERENCE_NODE == 5
Node.ENTITY_NODE == 6
Node.PROCESSING_INSTRUCTION_NODE == 7
Node.COMMENT_NODE == 8
Node.DOCUMENT_NODE == 9
Node.DOCUMENT_TYPE_NODE == 10
Node.DOCUMENT_FRAGMENT_NODE == 11
Node.NOTATION_NODE == 12
Though, we are only interested in three of them.
Node.ELEMENT_NODE == 1
Node.ATTRIBUTE_NODE == 2
Node.TEXT_NODE == 3
<ul id="optionList">
<li>This is the first option</li>
<li>This is the second</li>
<li>This is the third</li>
</ul>
In this example you can see the ul is considered an ELEMENT_NODE
- The id of the ul is considered an ATTRIBUTE_NODE
- The li are considered ELEMENT_NODE
- The text inside of the li are considered TEXT_NODE
###ACCESSING DOM ELEMENTS
The main question is, is the node unique to the document?
To grab an element by it's # (id) document.getElementById("someId");
What if you don't have an id on an element or have multiple elements you want to grab?
document.getElementsByTagName("li");
To create a variable equal to document.getElementById
var myElement = document.getElementById("someId");
How does it store the seperate elements by tag name? It stores each element in the dom as an array. It is assigned a value in the array based on its position in the DOM. These can be targeted specifically by adding square brackets with the position value in the array to the end of the variable.
var myListItems [ 0 ] = document.getElementsByTagName("li");
var myListItems [ 1 ] = document.getElementsByTagName("li");
var myListItems [ 2 ] = document.getElementsByTagName("li");
var myListItems [ 0 , 1 ] = document.getElementsByTagName("li");
ex. Array
0 | li
1 | li
2 | li
What if you create a variable with a tag that doesn't appear on the dom? It will still return an array, but the array will be empty. It won't even have a length of 1, it will have a length of 0.
1st ex. HTML
<h1>
<a id="mainTitle" href="index.html" title="Return to the home page">Welcome to the homepage</a>
</h1>
JS * Casing has to match in getElementById("");
var mainTitle = document.getElementById("mainTitle");
This will tell me what type of node mainTitle is
console.log("This is an element of type: ", mainTitle.nodeType );
This will tell me what text is written inside of mainTitle
console.log("The inner HTML is " , mainTitle.innerHTML );
This will tell me how many child nodes the mainTitle node has
console.log("Child nodes: ", mainTitle.childNodes.length );
This will tell me how many anchor tags are included in the entire DOM
var myLinks = document.getElementsByTagName("a");
console.log("Links: " , myLinks.length);
Restricting elements to retrieve in the DOM
<body>
<ul id="abc">
<li></li>
<li></li>
<li></li>
</ul>
<ol>
<li></li>
<li></li>
<li></li>
</ol>
</body>
This will select all of the li tags.
var myListItems = document.getElementsByTagName("li");
What if you don't want to select all 6, but only the 3 inside of the ul? Create a variable to target the element by its id
var myFirstList = document.getElementById("abc");
Instead of selecting from the DOM, or starting from the dom, you can then select/start from the variable just created above, which is the ul with the id of "abc"
var myListItems = myFirstList.getElementsByTagName("li");
Only the li tags inside of the ul id="abc" are selected
###CHANGING DOM CONTENT
Step 1 always going to be GET THE ELEMENT Attribute nodes and text nodes belong to elements. Attributes don't exist on their own in html, always contained within an element.
Changing attributes - 2 methods
getAttribute
myElement.getAttribute("align");
setAttribute
myElement.setAttribute("align","left");
ex.1 - set attributes to change attributes
<div id="mainContent"></div>
var mainContent = document.getElementById("mainContent");
mainContent.setAttribute("align","right");
ex.2 - get inner HTML to manipulate simple text
<h1>
<a id="mainTitle" href="index.html" title="Return to the home page">Welcome to Explore California!</a>
</h1>
var mainTitle = document.getElementById("mainTitle");
console.log(mainTitle.innerHTML);
ex.3 - Manipulating elements within elements is more difficult because innerHTML of outside elements renders the entire contents with tags.
<div id="sidebar">
<h2>Hello</h2>
<p>This is an example</p>
<div id="sidebarMenu">
<p>This is still an example</p>
</div>
</div>
var sidebar = document.getElementById("sidebar");
console.log(sidebar.innerHTML);
Would display in console:
<h2>Hello</h2>
<p>This is an example</p>
<div id="sidebarMenu">
<p>This is still an example</p>
</div>
###CREATE DOM CONTENT Much easier than passing innerHTML to elements within elements Steps
-
Create the element
-
Add it to the document using createElement("");
Create an li
var myNewElement = document.createElement("li");
li is created in space, not attached to the DOM so we append it to the child
myElement (ul id="abc");
myElement.appendChild(myNewElement);
Creating a text node
var myText = document.createTextNode("New list item text");
Similar to creating li, text node is created in space, not attached to the DOM so we append it to myNewElement (li)
myNewElement.appendChild(myText);
ex.1
<div id="trivia"></div>
Create the elements
var newHeading = document.createElement("h1");
var newParagraph = document.createElement("p");
Create child nodes
var h1Text = document.createTextNode("Did you know?");
var paraText = document.createTextNode("Some random fact.");
Add as child nodes to the new elements newHeading and newParagraph
newHeading.appendChild(h1Text);
newParagraph.appendChild(paraText);
Attach newHeading and newParagraph to the DOM
document.getElementById("trivia").appendChild(newHeading);
document.getElementById("trivia").appendChild(newParagraph);
Alternative to appendChild, although appendChild is the most common newElement = new element you just created existingElement is the element you select in which you want it to go before
parent.insertBefore(newElement, existingElement);
ex.2
<body>
<h1></h1>
<p></p>
<ul id="abc"> <!-- myElement -->
<li></li>
<li></li>
<li></li>
</ul>
</body>
Create new li in space
var myNewElement = document.createElement("li");
Grab second li with no id 0 = 1st 1 = 2nd in an array
var secondItem = myElement.getElementsByTagName("li")[1];
myElement.insertBefore(myNewElement, secondItem);
###JAVASCRIPT EVENT HANDLING
- Click events, assets loaded first, form submission making sure it's filled out
- Events have already been happening all along.
- When the page is loaded that's an event.
- When the user clicks a button that's another event.
- When they move their mouse that's a whole bunch of events.
- When they scroll the screen that's an event.
- When they click a form field that's an event.
- When they type every keypress is another event.
- Events are going on all the time, you have to decide which ones you care about.
Events are built into javascript ex onload onclick onmouseover onblur onfocus With javascript, we don't write the events, we write the event handlers We write the function and volunteer to listen or handle and event
#####WAYS TO HANDLE EVENTS
METHOD 1 (bad practice DO NOT USE, just like inline-styles...)
<button onclick="alert('hello, world');">
Run some JavaScript
</button>
METHOD 2 - MOST COMMON
element.event =
Example:
window.onload =
nameField.onblur =
myelement.onclick =
Anonymous function (very very common!)
myelement.onclick = function() {
//your event handler code
};
Think about the reason for functions. Usually we use a function to wrap up a bunch of code and give it a name so we can call it later. Here we are still using the word function to wrap up a bunch of code (whatevers in between the opening and closing curly braces) but we don't have to give it a name because were saying exactly when this gets executed. Which is when they click my element. So when this event happens we want to run this function (whatevers in this block of code) so naming it would be a waste of time.
METHOD 3 - HUGE BENEFIT/DRAWBACK
What event are we listening for, and what function you want to run, and false for some super advanced event handling. This method, you can have one event and multiple listeners or multiple events with one listener
document.addEventListener('click' myFunction, false);
document.addEventListener('click' myFunction, false);
document.removeEventListener('click' myFunction, false);
Problem - Area where there are still issues cross-browser Internet Explorer 8 and below
document.attachEvent('onclick' myFunction);
Write code to detect wether or not these functions exist. DO NOT DO THIS THOUGH! SEE BELOW
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;
}
}
Use jQuery or another library for cross-browser compatibility. Book : Javascript the good parts.
###WORKING WITH onClick AND onLoad EVENTS
document.onclick = function() {
alert("You clicked somewhere in the document");
}
function prepareEventHandlers() {
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the image");
}
}
Window is top level element. Parent of the DOM window.onload = function() { //prep anything we need to prepareEventHandlers(); }
###WORKING WITH onBlur AND onFocus EVENTS
var emailField = document.getElementById("email");
Click into it, if value is your email - set to blank
emailField.onfocus = function() {
if ( emailField.value == "your email") {
emailField.value = " ";
}
};
Leave field with value as blank - change back to your email
emailField.onblur = function() {
if ( emailField.value == " ") {
emailField.value = "your email";
}
};
###WORKING WITH TIMERS Slideshows, clocks, etc.
Two methods for timers - setTimeout and SetInterval (single / repeating)
function simpleMessage() {
alert("This is just an alert box");
}
setTimeout is in milliseconds
var timeoutHandle = setTimeout(simpleMessage,5000);
clearing the timeout on click
myImage.onclick = function() {
clearTimeout(timeoutHandle);
}
var myImage = document.getElementById("mainImage");
var imageArray = ["imageURL","imageURL2","imageURL3","imageURL4","imageURL5"];
var imageIndex = 0;
function changeImage() {
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
setInterval is also in milliseconds
var intervalHandle = setInterval(changeImage, 5000);
Clearing the setInterval on click
myImage.onclick = function() {
clearInterval(intervalHandle);
}
###COMMON JAVASCRIPT ERRORS
SYNTAX ERRORS
Missing () off myFunction
function myFunction( {
console.log("You called myFunction");
}
My function is not defined - called with a lowercase f in myFunction
function myFunction() {
console.log("You called myFunction");
}
window.onload = function() {
myfunction();
}
###DEBUGGING
- Setting a breakpoint - click on the line number
- Continue - Continues script running from breakpoint
- Step-into - Runs through code line by line
- Step-out - Goes back to whatever function called the - IE. if there was a loop set to 500 times, you wouldn't want to click step-into 500 times, you can test, and go back to the function
- Step-over - Execute this code, but if it's a function, don't go into it, execute the code and continue.
###ACCESSING FORM ELEMENTS
- Field values
- Field events
name of the form = frmContact (<form id="frmContact" name="frmContact")
<form id="frmContact" name="frmContact" method="post" action="Thanks.html">
document.forms.frmContact
Still a fan of getElementById - use this, not forms.frmContact (which is the name of the form, not the Id)
For textField or textArea
- main property myTextField.value -- get it or set it
- main events
- onfocus - Going into element
- onblur - Going out of element, always called when you leave even if you didn't change anything
- onchange - Same as onblur, but with changes
- onkeypress - On any keypress
- onkeydown - Keying down* /onkeyup - Keying up
*main property myCheckBox.checked (true or false) *main events *onclick *onchange *Most of the time you can use either or
*selectList *mySelect.type *select-one or select-multiple - Read from type attribute/property *main events *onchange - see which is selected by .selectedIndex for select-one *see which is selected by .options[x].selected gives you true or false
- Form events
- onsubmit - when user clicks submit button
- Check values of fields, etc. Validation!!
#####ENHANCING FORMS WITH JAVASCRIPT
When working with forms, we care about several things Values of individual form elements Events caused by individual form elements when you change them or move in and out Event of the entire form itself - Submitting the form
#####PREVENTING A FORM FROM BEING SUBMITTED 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; } }; }
window.onload = function() {
prepareEventHandlers();
}
#####CSS AND JAVASCRIPT Presentation and styles dynamic like content
myElement.style.color = "red";
myElement.style.left = "40px";
anything with hyphen in css becomes camelCase because javascript views hyphens as a minus sign
Setting the class
myElement.className = "someCSSclass";
clearing by setting to empty string
myElement.className = "";
###Understanding JAVASCRIPT STYLE
How should you write JavaScript
-
Your code should be readable
-
Your code should be consistent
-
You should know accepted best practices
-
Javascript is easily readable
-
Naming conventions
-
camelCase for variables and functions
-
One word lowercase
-
Two words camelCase
-
Three words camelCase
var score; var highScore; var evenHigherScore;
Usually multiple words for clarity. Usually Verb Noun format. Written the same way we work with the dom. CreateElement appendChild etc
function calculate() {...}
function calculateDistance() {...}
function checkFormFields() {...}
- var's can consist of letters, numbers, $, _;
- Objects use uppercase first letter
- Date
- Math
Brace style
if (x) {
//...
} else {
//...
}
while (x) {
//...
}
for (var i = 0; i < 10; i++) {
//...
}
function doStuff() {
//...
}
Use blocks of code
if (x > 500) {
alert("There's a problem");
resetEverything();
}
Define your function before you call them
#####wrong! Define functions before you call them!!!
function someFunction() {
otherFunction();
}
function otherFunction (x) {
//...
}
#####right! function otherFunction (x) { //... }
function someFunction() {
otherFunction();
}
- Always use semi colons when ending a statement
- Always use var when declaring a variable
###MINIFYING YOUR CODE
- COMPACTS CODE
- Removes comments
- Gets rid of line breaks
- Done to reduce file size
- Does not compile javascript to machine code, just making filesize smaller
- Does not obsuficate
###USING JAVASCRIPT CODE CHECKER
jslint
###JAVASCRIPT CODE LIBRARIES
- A bunch of javascript someone else wrote, so you don't have to
- Knowing jquery is a core skill for a javascript developer
###LINKING TO MULTIPLE JAVASCRIPT FILES
Own code, javascript libraries, order matters
###INTRO TO JQUERY
without jquery code often looks like this -
javascript
document.getElementsById("myDiv").className = "highlight";
Jquery
jQuery("#myDiv").addClass("highlight");
jQuery(".someClass")
jQuery("p")
jQuery("a")
jQuery("li")
jQuery("p.description")
words to add
:first :last :contains
Go through dom finding li's, picking last li before dom ends and adding a class of highlight
jQuery("li:last").addClass("highlight");
Go through dom finding paragraph tags, looking inside of those paragraph tag for the word packages and adding a class of highlight
jQuery("p:contains('packages')").addClass("highlight");
jQuery methods
jQuery("what to find").someAction();
Javascript vs jQuery .className and .addClass
it adds our new CSS class and keeps any that were there before so we can start stacking our CSS classes up on the elements
Not only do we have a add class we also have a remove class and a toggle class
jQuery("#myDiv").addClass("highlight");
jQuery("#myDiv").removeClass("highlight");
jQuery("#myDiv").toggleClass("highlight");
$ = jQuery
Select all p tags and hide with interval of 4000ms or 4s
$("p").hide(4000);
//jQuery takes care of animating without having to setInterval or setTimeout calls
$("p").fadeOut(4000);
$("p").fadeIn(4000);
$("p").Show(4000);
$("p").slideDown(4000);
$("p").slideUp(4000);
#####Events
simple click
$("#pageID").click(function() {
$("#pageID").text("You clicked me!");
});
add $(this) to refer to current element
$("h2").click(function() {
$(this).text("You clicked me!");
});
add effects - this makes each paragraph fade out when clicked.
$("p").click(function() {
$(this).fadeOut(2000);
});
Page load events - instead of window.onload()
$(document).ready(function () {
$("#pageId").text("The DOM is fully loaded.");
});
You don't have to worry about accidentally calling it multiple times.
$(document).ready(function () {
$("h1").css("color","red");
});
###USING A CONTENT DISTRIBUTION NETWORK (CDN) TO DELIVER JQUERY
- improved speed and redundancy
- improved bandwidth
- improved parallel downloads
- caching benefits
###HTML5 AND JAVASCRIPT
HTML5 - CONTENT (markup language)
- video & audio - BETTER SUPPORT FOR VIDEO AND AUDIO
- geolocation
- local storage - store more data than just simple cookies
- drag and drop - not just on pages, but between different pages
- canvas - Draw on the screen directly
- offline storage
- new form elements
New Javascript API's
CSS3 - PRESENTATION (style sheet language)
JavaScript - BEHAVIOR (programming language)
###JavaScript Additions not new
var a = document.getElementById("mainTitle");
var b = document.getElementsByTagName("li");
added get element by class name in html5
var c = document.getElementsByClassName("myClass");
Get multiple classes seperates by spaces
var d = document.getElementsByClassName("first second");
###HTML5 STORAGE
set
localStorage["username"] = name;
get
var name = localStorage["username"];
Offline Storage // Web SQL // IndexedDB
###WEB WORKERS
var worker = new Worker("anotherjavascriptfile.js");
// get ready to receive messages from the worker
worker.onmessage = function(e) {
console.log("The worker called me!");
};
// send messages to the worker
worker.postMessage("firstFunction");
Feature detection
if ( document.getElementsByClassName ) {
// it exists, we can use it
// ...
} else {
// it doesn't exist on this browser
}
###Modernizr
Put modernizr in the head
Modernizr creates a new javascript object called modernizr with over 40 javascript properties
A bunch of boolean values to tell you wether a certain html5 feature is supported
Video | true audio | true canvas | true localstorage | true webworkers | true websockets | true
if (modernizr.video) {
// yes - use HTML5 video
} else {
// perhaps replace with flash video
}
###Javascript to AVOID
document.write("Here is some text");
Run anytime after page has loaded, destroys the rest of the page
if (navigator.userAgent.indexOf('Netscape'))
// Browser sniffing code...
Old school or someone who doesn't know what they are doing
var a = "alert('";
var b = "hello";
var c = "')";
eval(a + b + c);
// Eval is a bad thing!
Pseudo-protocol
<a href="javascript:someFunction()">This</a>
If javascript is disabled, this is useless.
#####Regular Expressions
- CC# has right amt. of digits
- Email add has the right pattern
- Define certain words in a larger string
Create the regular Expressions
var myRE = /hello/;
//shorthand or
var myRE = new RegExp("Hello");
var myString = "Does this sentence have the word hello in it?";
if ( myRE.test(myString) ) {
alert("Yes");
}
Creating patterns
var myRE = /^hello/; // ^ at the start
var myRE = /hello$/; // $ at the end
var myRE = /hel+o/; // + once or more ex. "helo","hello","hellllllo"
var myRE = /hel*o/; // * zero or more ex. "heo","helo","hellllllllo"
var myRE = /hel?o/; // ? zero or one ex. "heo","helo"
var myRE = /hello|goodbye/; // either|or
var myRE = /he..o/; // . any character
var myRE = /\wello/; // \w alphanumeric or _
var myRE = /\bhello/; // \b word boundry
var myRE = /[crnld]ope/; // [...] range of characters
Define more complex patterns by stringing these regular expressions together
###Working with AJAX
Asynchronous javascript and XML AJAX == JavaScript
After a webpage has opened in a webpage in a users browser, Javascript can talk to the server and get specific information back without reloading the entire page
- Create the request
- Deal with any response
Creating the request
// Create the request
var myRequest
// Feature Check
if (window.XMLHttpRequest) {
// does it exist? We're in firefox, safari, chrome.
myRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// if not, we're in IE
myRequest = new ActiveXObject("MicrosoftXMLHTTP");
}
Create an event handler for our request to call back
myRequest.onreadystatechange = function() {
console.log("We were called!");
console.log(myRequest.readyState);
if (myRequest.readyState === 4) {
var p = document.createElement("p");
var t = document.createTextNode(myRequest.responseText);
p.appendChild(t);
document.getElementById("mainContent").appendChild(p);
}
};
Open and Send
myRequest.open("GET", "http://mysite.com/somedata.php", true);
Any parameters?
myRequest.send(null);
Use jquery for this stuff so you don't have to worry about crossbrowser compatibility...
###Introduction to Prototypes
Formalizing objects with constructors
function Player(n,s,r) {
this.name = n;
this.score = s;
this.rank = r;
}
Player.prototype.logInfo = function() {
console.log("I am:" , this.name);
}
Player.prototype.promote = function() {
this.rank++;
console.log("My new rank is:" , this.rank);
}
var fred = new Player("Fred",10000,5);
fred.logInfo();
fred.promote();
var bob = new Player("Bob",50,1);
bob.logInfo();
bob.promote();