Beginning Javascript

Class 2

Welcome!

Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.

Some "rules"

  • We are here for you!
  • Every question is important
  • Help each other
  • Have fun

Goals for the class

  • Week 1: Intro to JavaScript
  • Week 2: More JavaScript & the DOM
  • Week 3: Intro to jQuery
  • Week 4: AJAX and APIs

Useful References

Functions

Functions are re-usable
blocks (collections of statements)

Declare a function

  function sayHi(){
    console.log('Hi!');
  }
          
Call the function

  sayHi();
          

Arguments

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

Arguments

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

Return values

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

Variable Scope

The context where a specific variable is valid

JavaScript has two scopes:

  • Local - available in the function where it is defined
  • Global - available everywhere

Variable Scope: Local

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
          

Variable Scope: Global

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
          

Variable Scope: Best Practice

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
  }
          

Let's Develop It: Functions

  • Wrap the favorite activity calculator in a function called calculateActivity
  • calculateActivity should take an argument for the name of the activity
  • calculateActivity should take an argument for the times you do the activity per month
  • Call calculateActivity

Example

Are you done or really stuck?

Check out our example.

Adding JS to HTML: Inline


  <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 Develop It: Inline Events

Let's share information about another favorite activity

  • Add a link to your html page
  • Set the href attribute to #
  • Add an onclick event to the link that calls calculateActivity with arguments for a different activity.
  • Include return false if you want to prevent default behavior

Example

Are you done or really stuck?

Check out our example.

Loops

Sometimes you want to go through a piece of code multiple times

Why?

  • Showing a timer count down
  • Displaying the results of a search
  • Adding images to a slideshow

The while loop

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++;
  }
          
Review: '++' means increment by 1!

The while loop


  var x = 0;
  while (x < 5) {
    console.log(x);
    x++;
  }
          
Danger!!

What happens if we forget x++;?

The loop will never end!!

The for loop

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);
          }
          
Less danger of an infinite loop.
All conditions are at the top!

Array

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'];
            
The length property reports the size of the array:

  console.log(rainbowColors.length);
            

Arrays: accessing values

You can access items with "bracket notation".

The number inside the brackets is called an "index"

  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
            

Arrays: updating values

You can also use bracket notation to
change the item in an array:

  var awesomeAnimals = ['Corgis', 'Otters', 'Octopi'];
  awesomeAnimals[0] = 'Bunnies';
            
Or to add to an array:

  awesomeAnimals[3] = 'Corgis';
            
You can also use the push method:

  awesomeAnimals.push('Ocelots');
            

Loops and Arrays

Use a for loop to easily look at each item in an array:

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

Let's Develop It: Favorite Things

Output a list of your favorite things.

  • Add a new link to your html page with an onclick that calls the function favoriteThings
  • Create a JS function called favoriteThings
  • Create an array with some of your favorite things
  • Use a for loop to generate a sentence about your favorite things: "My favorite things are XX, YY, ZZ"
  • Output the sentence

Let's Develop It: Favorite Things

Output a list of your favorite things.

  • Bonus: add an 'and' in before the last item:
    "My favorite things are XX, YY, and ZZ"

Hints

  • Remember arrays are zero-indexed.
  • You need to use string concatenation to build your sentence.
  • You probably need an if/else to do the bonus.

Example

Are you done or really stuck?

Check out our example.

Objects

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

Objects: accessing values

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;
            

Objects: accessing values

Or using "bracket notation" (like arrays):

  var name = charlie['name'];
            
Non-existent properties will return undefined:

  var hometown = charlie.hometown;
            

Objects: changing values

Use dot or bracket notation with the assignment operator to change objects.

Change existing properties:

  charlie.name = "Chuck";
          
Or add new properties:

  charlie.hometown = "Peanuts";
            
You can also delete properties:

  delete charlie.hometown;
          

Arrays of Objects

Arrays can hold objects too!

  var peanuts = [
    {
      name: "Charlie Brown",
      pet: "Snoopy"
    },
    {
      name: "Linus van Pelt",
      pet: "Blue Blanket"
    }
  ];
That means we can use a for loop!
  for (var i = 0; i < peanuts.length; i++) {
    var peanut = peanuts[i];
    console.log(peanut.name + ' has a pet named ' +
                peanut.pet + '.');
  }

Objects in functions

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

Let's Develop It: My Connections

Share your connections (friends, pets, etc.).

  • Add a link that calls the function myConnections onclick
  • Add a myConnections javascript function
  • Create an array of connection objects, with their name, type (e.g. friend), and something they like.
  • Use a loop to go through each connection and describe them
  • Alert the results

Let's Develop It: My Connections

Share your connections (friends, pets, etc.).

  • Bonus: make a separate function that describes a connection

Hints

  • Use "\n" to insert a new line, if you want one.
  • Remember arrays are zero-indexed.
  • You need to use string concatenation to build your description.
  • For the bonus, use return to return the description.

Example

Are you done or really stuck?

Check out our example.

DOM

Document Object Model

  • A structural representation of the HTML elements on a web page
  • A way to interact with the HTML elements
    on a web page
  • Connects web pages to scripts or programming languages - most commonly JavaScript

DOM

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>

DOM: document

Entry point for the web page's content.
The root of the tree.

DOM: element

HTML nodes in the tree.

DOM: text

Text nodes in the tree.

DOM: document

Take a look at the tree.

DOM traversal: body

Get the body of your html


  document.body;
            

DOM traversal: body

Try it!

DOM traversal: parent

Get the parent of a node.


  document.body.parentNode;
            

Go up the tree

DOM traversal: parent

Try it!

DOM traversal: children

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

DOM traversal: children

Try it!

Sometimes whitespace leads to extra text nodes

DOM traversal: children

Get just the first child.


  document.body.firstChild;
          

DOM traversal: siblings

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

DOM traversal: siblings

Try it!

DOM searching

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.

DOM searching: id

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

DOM searching: id

Try it!

DOM searching: tag name

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

DOM searching: id

Try it!

DOM searching: tag name

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

Dom Node: attributes

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
            

Dom Node: attributes

Try it!

Dom Node: innerHTML

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.

Dom Node: innerHTML

Try it!

Dom: creating nodes

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

Dom Node: creating nodes

Try it!

DOM: window

Represents the window


  window.document;

  // How far has the user scrolled
  window.scrollX;
  window.scrollY;

  // How big is the window
  window.innerWidth;
  window.innerHeight;
          

DOM: window

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
  }
          

Let's Develop It

  • Put it all together
  • Modify your existing code to add new elements to the screen instead of firing an alert or outputting to console.log
  • You can change the HTML too.
  • Keep in mind how to find an element, how to append an element, and how to change the inner html of an element
  • There are lots of possible solutions! Be creative!

Hints

  • It can be easier to find a DOM element if it has an id.
  • The welcome message code needs to wait for the window to load before accessing the DOM.

Example

Are you done or really stuck?

Check out our example.

Keep in mind that this is one of many possible solutions.

Questions?

?