Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.
Some "rules"
Functions are re-usable
blocks (collections of statements)
function sayHi(){
console.log('Hi!');
}
sayHi();
Functions can take named arguments
function sayHi(name){
console.log('Hi' + name + '!');
}
sayHi('Jane');
sayHi('John');
// Pass variables as arguments
var name = 'Pip, the mouse';
sayHi(name);
Functions can take multiple named arguments
function addNumbers(num1, num2){
var result = num1 + num2;
console.log(result);
}
addNumbers(5, 6);
var number1 = 12;
var number2 = 15;
addNumbers(number1, number2);
Functions can return a value
function addNumbers(num1, num2){
var result = num1 + num2;
return result; //Anything after this line won't be read
}
var sum = addNumbers(5, 6);
The context where a specific variable is valid
JavaScript has two scopes:
Available in the function where it is defined
function addNumbers(num1, num2) {
var result = num1 + num2; // local
return result;
}
var sum = addNumbers(5, 6);
console.log(result); // undefined because it is outside of scope
Available everywhere
var result; // global
function addNumbers(num1, num2) {
result = num1 + num2;
return result;
}
var sum = addNumbers(5, 6);
console.log(result); // outputs 11 because it is global
Declare your variables at the top of their scope
to avoid problems.
function myFunction() {
// declare your variables at the top
var i, j;
var number = 10;
var string = "some string";
// code goes here
}
calculateActivity
calculateActivity
should take an argument for the
name of the activitycalculateActivity
should take an argument for the
times you do the activity per monthcalculateActivity
Are you done or really stuck?
Check out our example.
<html>
<head>
<title>My Site!</title>
</head>
<body>
My site!
<a href="#" onclick="alert('Hello World!'); return false;">
click me
</a>
</body>
</html>
Runs JavaScript when the event (click) occurs.
We'll talk about other events later.
Returning false prevents the default action.
Let's share information about another favorite activity
href
attribute to #
calculateActivity
with arguments for a different activity.return false
if you want to prevent
default behaviorAre you done or really stuck?
Check out our example.
Sometimes you want to go through a piece of code multiple times
Why?
The while loop tells JS to repeat statements
while a condition is true:
while (expression) {
// statements to repeat
}
var x = 0;
while (x < 5) {
console.log(x);
x++;
}
var x = 0;
while (x < 5) {
console.log(x);
x++;
}
What happens if we forget x++;?
The loop will never end!!
The for loop is a safer way of looping
for (initialize; condition; update) {
// statements to repeat
}
for (var i = 0; i < 5; i++) {
console.log(i);
}
An array is a data-type that holds
an ordered list of values of any type:
var arrayName = [element0, element1, ...];
var favoriteNumbers = [16, 27, 88];
var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green',
'Blue', 'Indigo', 'Violet'];
var luckyThings = ['Rainbows', 7, 'Horseshoes'];
console.log(rainbowColors.length);
You can access items with "bracket notation".
var arrayItem = arrayName[indexNum];
Arrays in JavaScript are zero-indexed,
which means
we start counting from zero.
var colors = ['Red', 'Green', 'Blue'];
var firstColor = rainbowColors[0]; // Red
var lastColor = rainbowColors[2]; // Blue
var awesomeAnimals = ['Corgis', 'Otters', 'Octopi'];
awesomeAnimals[0] = 'Bunnies';
awesomeAnimals[3] = 'Corgis';
awesomeAnimals.push('Ocelots');
var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green',
'Blue', 'Indigo', 'Violet'];
for (var i = 0; i < rainbowColors.length; i++) {
console.log("Index: " + i)
console.log("Value: " + rainbowColors[i]);
}
Output a list of your favorite things.
favoriteThings
favoriteThings
Output a list of your favorite things.
Are you done or really stuck?
Check out our example.
A data type that stores a collection of properties.
A property is an association between a name and value.
var objectName = {
propertyName: propertyValue,
propertyName: propertyValue,
...
};
var charlie = {
age: 8,
name: "Charlie Brown",
likes: ["baseball", "The little red-haired girl"],
pet: "Snoopy"
};
Access values of "properties" using "dot notation":
var charlie = {
age: 8,
name: "Charlie Brown",
likes: ["baseball", "The little red-haired girl"],
pet: "Snoopy"
};
var pet = charlie.pet;
var name = charlie['name'];
var hometown = charlie.hometown;
Use dot or bracket notation with the assignment operator to change objects.
charlie.name = "Chuck";
charlie.hometown = "Peanuts";
delete charlie.hometown;
Arrays can hold objects too!
var peanuts = [
{
name: "Charlie Brown",
pet: "Snoopy"
},
{
name: "Linus van Pelt",
pet: "Blue Blanket"
}
];
for (var i = 0; i < peanuts.length; i++) {
var peanut = peanuts[i];
console.log(peanut.name + ' has a pet named ' +
peanut.pet + '.');
}
You can pass an object into a function as a parameter
var peanut = {
name: "Charlie Brown",
pet: "Snoopy"
};
function describeCharacter(character){
console.log(character.name + ' has a pet named ' +
character.pet + '.');
}
describeCharacter(peanut);
Share your connections (friends, pets, etc.).
myConnections
onclickmyConnections
javascript functionShare your connections (friends, pets, etc.).
return
to return the description.Are you done or really stuck?
Check out our example.
Document Object Model
Look at the DOM reprentation of your page in the elements tab in the developer tools
In the DOM, web pages are like trees
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>My Page</h1>
<p>Some Text.</p>
</body>
</html>
Entry point for the web page's content.
The root of the tree.
HTML nodes in the tree.
Text nodes in the tree.
Take a look at the tree.
Get the body of your html
document.body;
Get the parent of a node.
document.body.parentNode;
Go up the tree
Get the children of a node.
var children = document.body.childNodes; // Array of child nodes
for(var i = 0; i < children.length; i++) {
var child = children[i]; // A child node
}
Go down the tree
Sometimes whitespace leads to extra text nodes
Get just the first child.
document.body.firstChild;
Get the siblings of a node.
var node = document.body.firstChild;
var next = node.nextSibling;
var previous = next.previousSibling;
Go across a branch of the tree
Finding every element on the page by traversing the tree is time consuming!
The document object also provides methods for finding DOM nodes without going one by one.
Get an element by its id
<div id="my-data">
the data
</div>
document.getElementById('my-data');
Ids are unique, so there should only be one
Get elements by their tag name
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
// Array of elements
var items = document.getElementsByTagName('li');
for(var i = 0; i < items.length; i++) {
var item = items[i];
}
Limit the scope of the search
<div id="important">
<p>important text</p>
</div>
<div>
<p>other text</p>
</div>
// All p elements
var allParagraphs = document.getElementsByTagName('p');
var scope = document.getElementById('important');
// p elements that are children of the scope element
var paragraphs = scope.getElementsByTagName('p');
You can get and set node attributes
<a id="gdi-link" href="http://girldevelopit.com">
Girl Develop It
</a>
var link = document.getElementById('gdi-link');
link.getAttribute('href'); // get attribute
var pghLink = 'http://girldevelopit.com/chapters/pittsburgh';
link.setAttribute('href', pghLink); //set attribute
Each node has an innerHTML property that can be used to get and set the content of the node.
<div id="important">
<p>important text</p>
</div>
var important = document.getElementById('important');
important.innerHTML; // get content
var newContent = '<strong>IMPORTANT TEXT!!!</strong>';
important.innerHTML = newContent; //set content
important.innerHTML += 'more text!'; // add to content
You can also add to the content.
The document object can create new nodes.
document.createElement(tagName);
document.createTextNode(text);
document.appendChild();
var newParagraph = document.createElement('p');
var paragraphText = document.createTextNode('My new text!');
newParagraph.appendChild(paragraphText);
document.body.appendChild(newParagraph);
Represents the window
window.document;
// How far has the user scrolled
window.scrollX;
window.scrollY;
// How big is the window
window.innerWidth;
window.innerHeight;
We don't have access to the DOM until the window loads.
Immediately running JS that depends on the DOM leads to problems.
window.onload = function() {
// Put JS that runs on page load here
}
Are you done or really stuck?
Check out our example.
Keep in mind that this is one of many possible solutions.