Intro to JavaScript

Philly Tech Week Dev Day

April 23, 2015


www.ahoef.co/intro-to-js/slides
www.ahoef.co/intro-to-js/demo-files.zip

Alexandra Hoefinger — @ahoefinger

What is JavaScript?


  • A programming language for building dynamic webpages that respond to input from users
  • First emerged on the web in 1995 with Netscape Navigator 2.0
  • Now one of the most common languages across the web
  • An essential part of a web developer's toolkit

Including JS — Script Tags


You can mix JavaScript and HTML. The script tag tells your browser the code inside is JavaScript, not HTML



<script>
    CODE GOES HERE
</script>
				

Including JS — External Files


Just like CSS, you can split a long block of JavaScript into its own file.



<script src="path/to/your/file.js"></script>
				

console.log


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>
				

Comments


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>
				

Exercise


  • Add a console.log within the script tags in index.html
  • Add a console.log in site.js

Variables

A variable is a place to store values


Variable Values


  • When you first create a variable, it does not have a value (it is null).
  • You can set a value for a variable.
  • Variables can hold different types of information, like words, numbers, and collections of data.
  • The value of a variable can change over time.

Naming Variables


  • The variable name is case-sensitive.
  • A new variable needs to have a unique name.
  • Variable names need to start with a letter, $, or _.
  • Variable names can only be made of letters, numbers, $, or _.

Declaring a Variable

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;
				

Using a Variable


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);
			

Numbers & Math



var numberOfKittens = 5;
var numberOfPuppies = 4;
var numberOfAnimals = numberOfKittens + numberOfPuppies;
				

Arithmetic Operators

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.

Exercise


Create two variables and try some math!

Strings


Variable can be strings, which are groups of characters in quotes.



var cityName = 'Philadelphia';
				

String Operators


You can put strings together with a +, the concatenation operator.



var cityName = 'Philadelphia';
var cityAndState = cityName + ' Pennsylvania';
console.log(cityAndState); //Outputs 'Philadelphia Pennsylvania'
				

String Operators

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>
				

Exercise


Create two variables, a first name and a last name, and then put them together to make a full name

Functions

Functions are separable, reusable pieces of code.


Using Functions




// declare the function
function greet(){
  console.log("Hey there!");
}


// call the function
greet();
			

Arguments

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
				

Variable Scope

The scope of a variable is how long the computer will remember it.

Global Scope

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"
                

Local Scope

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

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.

The if statement

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!');
}
                

Comparison Operators

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.

Watch out!



Don't mix up = and ==

Exercise

Make a variable called "temperature." Write some code that tells you to put on a coat if it is below 50 degrees.

The if/else statement

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.');
}
                

The if/else if/else statement

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.');
}
                

Logical Operators

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.

Using logical operators

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 loops

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;
}
                

Infinite Loops

Make sure something changes in the loop, or your loop will go on forever...

For loops

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

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'];
                

Array Length

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
                

Using Arrays

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'
                

Changing arrays

You can use bracket notation to change an item in an array


var myFavoriteThings = ['Broccoli', 1024, 'Sherlock'];
myFavoriteThings[0] = 'Asparagus';  

//outputs ['Asparagus', 1024, 'Sherlock'];          
                

Expanding arrays

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'];             
                

Iterating through arrays

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]);
}              
                

Exercise


Use a loop to log a list of all your favorite foods

Objects

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}
}; 
              

Accessing Objects

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'];
              

Changing Objects

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;
              

Arrays of Objects

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.');
}
              

Arrays of Objects

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);
              

Exercise


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.

The DOM Tree

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.

The DOM: Sample Code


<!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>
                

The DOM: Sample Model

Simple DOM Tree

DOM Access

Your browser automatically builds a Document object to store the DOM of a page. To change a page:

  1. Find the DOM node and store it in a variable
  2. Use methods to manipulate the node

DOM Access: By Id

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');
              

Traversing the DOM



document.getElementById('presentation');
document.getElementsByClassName('slide');
document.getElementsByTagName('body');
document.querySelectorAll('a');
document.querySelector('img');


More on JS DOM Access!

What is jQuery?


  • A library of predefined JavaScript functions
  • A tool that prevents developers from having to reinvent the wheel
  • A well-supported cross browser solution
  • Not a replacement for an understanding of JavaScript

Example: JavaScript


To hide images:

var elems = document.getElementsByTagName("img");
for (var i = 0; i< elems.length; i++) {
  elems[i].style.display = "none";
}

Example: jQuery


To hide images:

$('img').hide();

Including jQuery


<script src="js/jquery.js"><script>

OR


  • Use a content distribution network for a cached file
<script src="http://code.jquery.com/jquery-2.1.3.js"><script>

Document Readiness

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.
});

Anatomy of a jQuery call

$('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

Anatomy of a jQuery call


$('img').hide();

  • $('img') is a selector
  • .hide() is a method

Selectors


All CSS selectors are valid, plus some extras!


30 CSS Selectors
jQuery Docs on Selectors

Methods

There are many jQuery methods- like tools in a toolkit!


  • Getting/changing content within elements
  • Finding/changing elements themsleves
  • Changing attributes
  • Getting/changing dimensions & positions
  • Creating animations
  • Events


jQuery Docs on Methods

Examples:


$('.hero img').remove();
          
          $('#banner > span').hide();
          
          $('#banner').children().hide();
          
          $('img:not(.hero img)').fadeOut();
        

Examples:


$('.hero img').attr('src');
          
          $('#banner > span').addClass('visible');
          
          $('#banner').children().append('!');
          
        

Reading elements & their properties


<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"

Changing elements & their properties

<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'});

Why not just css/html?

  • Sometimes you don't have access to those files
  • Dynamic Content
  • Conditionals
var isMobile = screen.width <= 640;

if (isMobile) {
  $('.desktop-nav').hide();
  $('.mobile-nav').show();
}
      

Events


Interaction

  • Most events happen via the .on() method, which usually takes two args.
  • The first arg is the event, passed in as a string
  • The second arg is a function that will run when the event happens, called an event handler
  • 
    $('button').on('click', function() {
      console.log('the button was clicked!');
    });
    

jQuery UI & Plugins

  • jQuery UI offers more advanced interaction methods. It's very well documented, but can be heavy on pageload. Only load in pieces you need!

  • jQuery is open source and widely used, so there are many many plugins available (of varying quality and levels of documentation)
    • date pickers, slideshows, accordions, much more!


http://plugins.jquery.com/

Using Plugins

  • Download the plugin and associated files from the site or github repo
  • Copy them into your project folder
  • In the HTML, reference any associated CSS files
  • In the HTML, add a script tag for the jQuery plugin itself
  • In the JavaScript, call the jQuery plugin on your DOM

Exercise!

Add a slideshow using Slick.js!

  • Use any of the images in the demo-files image folder, or any of your own images
  • Test out some of the different display/interaction options Slick has

Next Steps

Questions?

?

Thank You!


Get in touch!

@ahoefinger

alexandra.hoefinger@gmail.com