9/27/2018

Exercise 13

Record Class

Any questions from the assignment?

JavaScript Loops

Loops in JavaScript are used to execute the same statement multiple times.

There are two types of Loops

  • For Loops
  • While Loops

The For Loop

The for loop is most often used when dealing with collections. It is possible to not even execute if the condition evaluates to true.

Syntax

for ( statement 1; statement 2; statement 3; ){

//Code Block

}

Code Samples


    var x = [1, 2, 3, 4];
    for(var i = 0; i < x.length; i++){
        console.log(x[i]);
    }
                    

    var x = [1, 2, 3, 4];
    var i = 0;
    for(; i < x.length; i++){
        console.log(x[i]);
    }
                    

More Examples


    var names = ['Jon', 'Benjamin', 'Kristin'];
    var html = "<ul>"
    for( var i = 0; i < names.length; i++){
        html = html + '<li>' + names[i] + '</li>'
    }
    html = html + '</ul>';

                        

More Examples


var names = [
    { firstname: 'John', lastname: 'Doe'},
    { firstname: 'Jane', lastname: 'Doe'}
    ];
var html = "<ul>"
for( var i = 0; i < names.length; i++){
    html = html + '<li>' + names[i].firstname + ' ' + names[i].lastname  + '</li>'
}
html = html + '</ul>';
                        

Reverse Loops


    var array = [1,2,3,4,5]
    for(var i = array.length;i--;){

    }
    

Clever shorthand where the 2nd statement will eval to false when i === 0.

Do and While Loops

Do and While loops are easier to read, but require more care to code properly.

A While Loop

May not execute depending on the condition.


    var i = 0;
    while(i < 25){
        console.log('i is equal to ' + i);
        i++
    }

Do Loop

Will always execute at least once.


    var i = 0;
    do{
        console.log('i is equal to ' + i);
        i++
    }
    while (i < 25);

More Examples


    var condition = false;
    var i = 0;
    while(condition == false){
        if (i > 10){
           condition = true;
        }

        i++
    }

Dangers of Do and While Loops

Infinite Loops

JavaScript Scope

Scope is the collection of variables, objects and functions you have the ability to access.

Local Scope

Local scope is a group of items that can only be accessed within the context it is declared.



    function testing(){
        var x = 0;

        console.log(x); //logs 0
    }

    testing();

    console.log(x);  // Causes an error



Global Scope

Global scope items can be accessed by all JavaScript on the page.



    var x = 0;
    function testing(){

        console.log(x); //logs 0
    }

    testing();

    console.log(x);  //logs 0;



JavaScript Dates

Dates are variable types that represent a date and time inside of JavaScript.

Epoch Time

Dates are stored as the number of milliseconds since January 1, 1970.

Example: 4/5/2017 is roughly - 1491415025702

Example : 1/1/1777 is roughly - -6090400800000

Date Declaration

//Creates a date variable that is set to now;
var now = new Date();         
// Wed Apr 05 2017 12:57:05 GMT-0500 (Central Daylight Time);
var newDate = new Date(1491415025702); 
//Tue Aug 17 2010 12:09:36 GMT-0500 (Central Daylight Time)
var newDate = new Date("2010/08/17 12:09:36"); 
//Fri Jan 01 2010 00:00:00 GMT-0600 (Central Standard Time)
var newDate2 = new Date("1/1/2010");

The Ternary Operator

AKA: Single Line If Else Statement

condition ? expression1 : expression2

This gets replaced with


var isValid;
if (name.length > 0){

    isValid = true;

}else{

    isValid = false;

}
            

This


var isValid = (name.length > 0) ? true: false;
            

Where can you use this?

Simple Validation


    var isValid = (name.length > 0) ? true: false;
            

Age Gate


    var oldEnough = (age > 17) ? true: false;
            

    var userType = (isRegistered) ? "Existing User": "New User";
            


JavaScript Styles

You can access styles and change an element's styles inside of css.

object .style .[CSS Property]

Example


    var elm = document.getElementById('id');
    elm.style.color = '#000000';
    elm.style.padding = '20px';

                         

Full Reference

Remember Hyphens Aren't Valid in JavaScript


    #div{
        background-color:#fff;
        margin-bottom: 20px;
    }
                            

    var elm = document.getElementById('div');
    elm.style.backgroundColor = '#fff';
    elm.style.marginBottom = '#fff';
                            

See the Pen UA-ITR-JS-Styles by Jon (@Middaugh) on CodePen.

JavaScript classList

The class list property is used to add and remove classes from HTML elements. It acts like an array, but the methods are easier to understand

classList Methods

  • .add('class1', 'class2', ..) - Adds one or more classes to the class list
  • .contains('class') - returns true or false if the element contains the class.

classList Methods Continued

  • .item(index) - Returns the index of the class if it is inside the element list
  • .remove('c1', 'c2', ....) - removes one or more classes from an element
  • .toggle('c1') - Adds or removes class based on if it exists or not

Examples


    var elm = document.getElementById('id');

    elm.classList.add('new-class'); //Adds the new class

    console.log(elm.classList.contains('new-class')); //Outputs true

    elm.classList.remove('new-class'); //Adds the new class

    console.log(elm.classList.contains('new-class')); //Outputs false

See the Pen UA-ITR-JS-AddRemoveClasses by Jon (@Middaugh) on CodePen.

Event Listeners

Event listeners allow us execute JavaScript when the user interacts with the document.

  • addEventListener
  • removeEventListener

addEventListener

Syntax

element .addEventListener ('click', function)

See the Pen KZOGBJ by Jon (@Middaugh) on CodePen.

Document Ready

The safest way to execute JavaScript is to wait for the document to load, and then execute your JavaScript.

Old Method


       <body onload="load()">
    

We may not always have access to the HTML though.

New Method


if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading"){
    fn();
} else {
    document.addEventListener('DOMContentLoaded', fn);
}

This ensures your code is consistency executed wherever it is placed.

Exercise 13

>