Philly Tech Week Dev Day
April 23, 2015
Alexandra Hoefinger — @ahoefinger
You can mix JavaScript and HTML. The script tag tells your browser the code inside is JavaScript, not HTML
<script>
CODE GOES HERE
</script>
Just like CSS, you can split a long block of JavaScript into its own file.
<script src="path/to/your/file.js"></script>
A common way to view JavaScript output in the browser's console
<script>
console.log('Hello World!');
console.log('JavaScript is great!');
console.log('Welcome to the console!');
</script>
You can leave comments in your code—notes that people can read and computers will ignore.
<script>
/*I can wrap long comments
with multiple lines
like this*/
console.log('Hello World!'); //Or mark short comments like this
</script>
A variable is a place to store values
To declare (create) a variable, just type the word "var" and the variable name.
var numberOfKittens;
It is a good idea to give your variable a starting value. This is called initializing the variable.
var numberOfKittens = 5;
Once you have created a variable, you can use it in your code. Just type the name of the variable.
var numberOfKittens = 5;
console.log (numberOfKittens);
var numberOfKittens = 5;
var numberOfPuppies = 4;
var numberOfAnimals = numberOfKittens + numberOfPuppies;
Example | Name | Result |
---|---|---|
-a | Negation | Opposite of a. |
a + b | Addition | Sum of a and b. |
a - b | Subtraction | Difference of a and b. |
a * b | Multiplication | Product of a and b. |
a / b | Division | Quotient of a and b. |
a % b | Modulus | Remainder of a divided by b. |
Create two variables and try some math!
Variable can be strings, which are groups of characters in quotes.
var cityName = 'Philadelphia';
You can put strings together with a +, the concatenation operator.
var cityName = 'Philadelphia';
var cityAndState = cityName + ' Pennsylvania';
console.log(cityAndState); //Outputs 'Philadelphia Pennsylvania'
You can also use += to add things to the end of a string.
var kittensName = 'Admiral ';
kittensName += ' Snuggles';
console.log(kittensName); //Outputs 'Admiral Snuggles'
</script>
Create two variables, a first name and a last name, and then put them together to make a full name
Functions are separable, reusable pieces of code.
// declare the function
function greet(){
console.log("Hey there!");
}
// call the function
greet();
Functions can accept input values, called arguments.
function callKitten (kittenName){
console.log('Come here, ' + kittenName + '!');
}
callKitten ('Fluffy'); //outputs 'Come here, Fluffy!'
function addNumbers(a, b) {
console.log(a + b);
}
addNumbers(5,7); //outputs 12
addNumbers(9,12); //outputs 21
The scope of a variable is how long the computer will remember it.
A variable declared outside a function has a global scope and can be accessed anywhere, even in a function.
var name = "Ali";
function greet() {
console.log("Hey there, " + name);
}
greet(); //Outputs "Hey there, Ali"
A variable declared within a function has a local scope and can only be accessed within that function.
function greet() {
var name = "Ali";
console.log("Hey there, " + name);
}
greet(); //Outputs "Hey there, Ali"
console.log (name + ' is my name.'); //Won't work
Boolean variables represent the logical values True and False
var grassIsGreen = true;
var skyIsGreen = false;
If you try to use another variable as a boolean, JavaScript will guess. The number 0, the empty string '', undefined, and null are considered false, everything else reads as true.
Use if to decide which lines of code to execute, based on a condition.
if (condition) {
// statements to execute
}
var bananas = 5;
if (bananas > 0) {
console.log ('You have some bananas!');
}
Example | Name | Result |
---|---|---|
a == b | Equal | TRUE if a is equal to b (can be different types). |
a === b | Identical |
TRUE if a is equal to b, and the same type. |
a != b | Not equal | TRUE if a is not equal to b (can be different types). |
a !== b | Not identical |
TRUE if a is not equal to b, or they are not the same type. |
a < b | Less than | TRUE if a is strictly less than b. |
a > b | Greater than | TRUE if a is strictly greater than b. |
a <= b | Less than or equal to | TRUE if a is less than or equal to b. |
a >= b | Greater than or equal to | TRUE if a is greater than or equal to b. |
Don't mix up = and ==
Make a variable called "temperature." Write some code that tells you to put on a coat if it is below 50 degrees.
Use else to provide an alternate set of instructions.
var age = 28;
if (age >= 16) {
console.log ('You are old enough to drive!');
} else {
console.log ('Sorry, but you have ' + (16 - age) +
' years until you can drive.');
}
If you have multiple conditions, you can use else if.
var age = 20;
if (age >= 35) {
console.log('You can vote AND hold any place in government!');
} else if (age >= 25) {
console.log('You can vote AND run for the Senate!');
} else if (age >= 18) {
console.log('You can vote!');
} else {
console.log('You can\'t vote, but you can
still write your representatives.');
}
Example | Name | Result |
---|---|---|
a && b | And | TRUE if both a and b are TRUE . |
a || b | Or | TRUE if either a or b is TRUE . |
! a | Not | TRUE if a is not TRUE . |
You can use these operators to combine conditions.
var bananas = 5;
if (bananas >=2 && bananas <7) {
console.log ('You have a reasonable number of bananas');
} else {
console.log ('Check your banana supply');
}
While will repeat the same code over and over until some condition is met.
var bottlesOfBeer = 99;
while (bottlesOfBeer >= 1) {
console.log (bottlesOfBeer + ' bottles of beer on the wall');
bottlesOfBeer = bottlesOfBeer - 9;
}
Make sure something changes in the loop, or your loop will go on forever...
For loops are very similar, but you declare a counter in the statement.
//will count 1 to 10
for (var i = 1; i <= 10; i++) {
console.log (i);
}
Arrays are ordered lists of values.
var arrayName = [element0, element1, ...];
You can put different types of data into an array.
var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green',
'Blue', 'Indigo', 'Violet'];
var lotteryNumbers = [33, 72, 64, 18, 17, 85];
var myFavoriteThings = ['Broccoli', 1024, 'Sherlock'];
The length property tells you how many things are in an array
var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green',
'Blue', 'Indigo', 'Violet'];
console.log(rainbowColors.length);
//outputs 7
You can access items with "bracket notation" by using the position of the object you want. Programmers start counting at zero.
var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green',
'Blue', 'Indigo', 'Violet'];
var firstColor = rainbowColors[0]; //outputs 'Red'
var lastColor = rainbowColors[6]; //outputs 'Violet'
You can use bracket notation to change an item in an array
var myFavoriteThings = ['Broccoli', 1024, 'Sherlock'];
myFavoriteThings[0] = 'Asparagus';
//outputs ['Asparagus', 1024, 'Sherlock'];
Arrays do not have a fixed length. You can use "push" to add something to an array.
var myFavoriteThings = ['Broccoli', 1024, 'Sherlock'];
myFavoriteThings.push('Dancing');
//outputs ['Broccoli', 1024, 'Sherlock', 'Dancing'];
Use a for loop to easily process each item in an array.
var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'];
for (var i = 0; i < rainbowColors.length; i++) {
console.log(rainbowColors[i]);
}
Use a loop to log a list of all your favorite foods
Objects let us store a collection of properties.
var objectName = {
key: value,
key: value,
...
};
var aboutMe = {
hometown: 'Atlanta, GA',
hair: 'Auburn',
likes: ['knitting', 'code'],
birthday: {month: 10, day: 17}
};
You can retrieve values using "dot notation"
var aboutMe = {
hometown: 'Atlanta, GA',
hair: 'Auburn'
};
var myHometown = aboutMe.hometown;
Or using "bracket notation" (like arrays)
var myHair = aboutMe['hair'];
You can use dot or bracket notation to change properties
var aboutMe = {
hometown: 'Atlanta, GA',
hair: 'Auburn'
};
aboutMe.hair = 'blue';
Add new properties
aboutMe.pet = 'cat';
Or delete them
delete aboutMe.pet;
Since arrays can hold any data type, they can also hold objects
var myCats = [
{name: 'Lizzie',
age: 18},
{name: 'Daemon',
age: 1}
];
for (var i = 0; i < myCats.length; i++) {
var myCat = myCats[i];
console.log(myCat.name + ' is ' + myCat.age + ' years old.');
}
Just like other data types, objects can be passed into functions:
var lizzieTheCat = {
age: 18,
furColor: 'grey',
likes: ['catnip', 'milk'],
birthday: {month: 7, day: 17, year: 1996}
}
function describeCat(cat) {
console.log('This cat is ' + cat.age + ' years old with ' + cat.furColor + ' fur.');
}
describeCat(lizzieTheCat);
Create an object to hold information on your favorite recipe. It should have properties for recipeTitle (a string), servings (a number), and ingredients (an array of strings).
Try logging some information about your recipe.
We model the nested structure of an HTML page with the DOM (Document Object Model) Tree. The browser makes a "map" of all the elements on a page.
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<style>
h1 {
color: red;
}
</style>
</head>
<body>
<h1>My Page</h1>
<p>Hello World!</p>
<img src="http://placekitten.com/200/300" alt="cat"/>
</body>
</html>
Your browser automatically builds a Document object to store the DOM of a page. To change a page:
You can find nodes by id using the method:
document.getElementById(id);
To find:
<img id="kittenPic" src="http://placekitten.com/200/300" alt="cat"/>
We would use:
var imgKitten = document.getElementById('kittenPic');
document.getElementById('presentation');
document.getElementsByClassName('slide');
document.getElementsByTagName('body');
document.querySelectorAll('a');
document.querySelector('img');
More on JS DOM Access!
To hide images:
var elems = document.getElementsByTagName("img");
for (var i = 0; i< elems.length; i++) {
elems[i].style.display = "none";
}
To hide images:
$('img').hide();
<script src="js/jquery.js"><script>
OR
<script src="http://code.jquery.com/jquery-2.1.3.js"><script>
Most everything you want to do with jQuery requires the DOM to be fully loaded.
The browser renders the markup from top to bottom, then triggers a DOMReady event.
$(document).ready(function() {
// Handler for .ready() called.
});
$(function() {
// Handler for .ready() called.
});
$('img').hide();
$() Global jQuery function. Alternately "jQuery()" Used to trigger all jQuery functionality.
'img' Argument being passed into the global jQuery function. In this case, a selector to return all 'img' elements. Also accepts variables and html strings. Returns a jQuery collection/object
.hide() jQuery method to hide the element by adding a style of 'display: none;'
; Syntax to conclude a statement
$('img').hide();
All CSS selectors are valid, plus some extras!
There are many jQuery methods- like tools in a toolkit!
$('.hero img').remove();
$('#banner > span').hide();
$('#banner').children().hide();
$('img:not(.hero img)').fadeOut();
$('.hero img').attr('src');
$('#banner > span').addClass('visible');
$('#banner').children().append('!');
<a href="http://www.google.com" style="color: green;">Google</a>
$('a').text(); "Google"
$('a').attr('href'); "http://www.google.com"
$('a').css('color'); "green"
<a href="http://www.google.com" style="color: green;">Google</a>
$('a').text('Yahoo!');
$('a').attr('href', 'http://www.yahoo.com');
$('a').css({'color': 'purple', 'text-decoration': 'underline'});
var isMobile = screen.width <= 640;
if (isMobile) {
$('.desktop-nav').hide();
$('.mobile-nav').show();
}
$('button').on('click', function() {
console.log('the button was clicked!');
});
Add a slideshow using Slick.js!
alexandra.hoefinger@gmail.com