prisskreative
4/1/2015 - 7:25 PM

Javascript Ironhack

Javascript Ironhack

function onCelebrateClick () {
  console.count('Holiday! Celebrate! All day!');
 
  // Empty the body to remove old content.
  $('body').empty();
 
  // Append new content to the body.
  // Need to add slash before newlines in JavaScript strings
  $('body').append(
    '<h1>PAAAAAHHHHHTYYYYY</h1>\
    <h2>YOU HAVE WON EVERYTHING EVAH</h2>\
    <p>Get busy</p>\
    <button class="js-restore">Restore</button>'
  );
 
  // Register any event handlers for new content.
  $('.js-restore').on('click', onRestoreClick);
}
 
// Add hover event to celebrate button
$('.js-celebrate').on('mouseover', onCelebrateClick);
 
 
function onRestoreClick () {
  // Empty the body to remove old content.
  $('body').empty();
 
  // Restore old content to the body.
  $('body').append(
    '<h1>Item #50</h1>\
    \
    <h2>You’ve won the item!</h2>\
    <button class="js-celebrate">Celebrate</button>'
  );
 
  // Register any event handlers for new content.
  $('.js-celebrate').on('mouseover', onCelebrateClick);
}
 
 
console.log('End of file');
 
function averageColon (numbers) {
  console.log(numbers);
 
  // Split the string into an array of number-strings
  var numberStrArr = numbers.split(':');
 
  console.log(numberStrArr);
 
 
  // Transform the number-strings into numbers
  function toNumber (str) {
    return Number(str);
  }
 
  var numberArr = numberStrArr.map(toNumber);
 
 
  // numberStrArr = [ '80', '70', '90', '100' ]
  // var numberArr = [
  //   toNumber('80'),
  //   toNumber('70'),
  //   toNumber('90'),
  //   toNumber('100')
  // ]
 
  console.log(numberArr);
 
 
  // Add the numbers together with .reduce()
  function addify (accumulator, number) {
    return accumulator + number;
  }
 
  var sum = numberArr.reduce(addify);
 
  // numberArr = [ 80, 70, 90, 100 ]
  // var result1 = addify(80, 70);
  // var result2 = addify(result1, 90);
  // var result3 = addify(result2, 100);
  // var sum = result3;
 
  console.log(sum);
 
 
  // Average out the amount by how many numbers I'm working with
  var average = sum / numberArr.length;
 
  return average;
}
 
console.log(averageColon('80:70:90:100'));
console.log(averageColon('3:127:4:42:54'));

Nizar's JavaScript Methodology

  1. Move <script> tags to the end of the <body> tag.
  2. Think about the desired experience
  • Which page does this happen on?
  • Which users does this happen for?
  • What is the trigger for this to happen?
  1. Add any HTML elements necessary for the trigger.
  2. Selecting those elements.
  • Add a selector to the HTML elements that is for JavaScript's use only.
  • Select the element in the inspector.
  • Add the jQuery code for selection to my JavaScript file.
  1. Add events to the selector.
  2. Fill in my event handlers with the desired code.
  • (any JavaScript code works, including more jQuery calls).

Example HTML

<!-- Use class names prefixed by "js-" to distiguish them as for JavaScript -->
<button class="js-celebrate">Celebrate</button>

Example JavaScript

// Defining named functions helps keep track of parentheses
function onCelebrateClick ()
{
  console.count('Holiday! Celebrate!');

  // Adding additional HTML is just a question of building it as a string.
  var html = '<p>Paragraph</p>';

  $('body').append(html);
}

// Remember that class selectors start with "."
$('.js-celebrate').on('click', onCelebrateClick);
$('.js-pizza').on('click', function () {
  // Grab the currently selected option from dropdown
  var moveOption = $('.js-move-option').val();
 
  // If fade selected, fade
  if (moveOption === 'fade')
  {
    $('.js-hide-me').fadeToggle(3000);
  }
 
  // If slide selected, slide
  else if (moveOption === 'slide')
  {
    $('.js-hide-me').slideToggle(3000);
  }
 
  // Otherwise just hide/show immediately
  else
  {
    // DONT send toggle a number
    $('.js-hide-me').toggle();
  }
});
 
// Printing is with console.log
//-------------------------------
 
console.log('This is me printing.');
console.log(42);
console.log('Hello', 'Hola');
 
 
// Comments
//-------------------------------
 
// Single line comment
 
/*
  This is a multi-line comment
  (you probably shouldn't use these).
  Use CMD + / or CTRL + / on your editor.
  (if your editor doesn't have a way to do this,
  throw it away.)
*/
 
 
 
// Variables
//-------------------------------
 
// The first time you use a variable, you need to prefix it with var.
var first;
 
console.log('No initial value for first', first);
 
// after that you can just use it.
first = 'FIRST VARIABLE';
 
console.log('Re-defined value for first', first);
 
 
var second = 'SECOND VARIABLE';
 
console.log('Initial value for second', second);
 
second = 'SECOND SECOND VARIABLE';
 
console.log('Re-defined value for second', second);
 
 
// You can't use variables until you've "vared" them
// console.log('VALUE OF THIRD', third);
 
 
// Strings
//-------------------------------
 
 
// Double quotes and single quotes are the same
 
// Except that you need to escape a single quote inside a single quoted string
'Nizar\'s Pizza'
'Nizar likes "coding"'
 
// You need to escape a double quote inside a double quoted string
"Nizar's Pizza"
"Nizar likes \"coding\""
 
// That means that there is no string interpolation #{} in JavaScript.
// You need to stitch together your strings with +
"Nizar" + " other string " + "etc"
 
 
 
// Comparisons
//-------------------------------
 
// Use === because...
console.log(0 == '0');
console.log(0 == '');
console.log('0' == '');
 
// WAT
// == transforms the type of one to match the other and then compares
 
 
 
// if .. else
//-------------------------------
 
var food = 'pizza';
 
if (food === 'pizza')
{
    console.log('Oh dear lord, pizza.');
}
// NOT elsif
else if (food === 'cookies')
{
    console.log('Mmmm cookies.');
}
else {
    console.log('What the hell...');
}
 
 
// Functions
//-------------------------------
 
// declare function with the function keyword
function some_method ()
{
  console.log('Do stuff. Important stuff.');
}
 
 
// the function name becomes a variable
console.log(some_method);
 
 
// to call it you need PARENTHESES
some_method();
 
 
 
// Loops
//-------------------------------
 
var i = 1;
 
// While this is true, keep running the instructions.
while (i <= 100)
{
  console.log('while: I IS', i);
  // Change the variable used in the condition so that it stops eventually.
  i += 1;
}
 
console.log('WHILE LOOP IS OVER', i);
 
 
 
// ORDER in which things happen in a for
// [5], [6], [7] repeat over and over
// for ([1]; [2] [5]+; [4] [7]+)
// {
//   [3] [6]+
// }
//
// [8]
 
// First section of for is the starting point
// Second section is the condition (just like in a while loop)
// Third section is to change the variable in the condition
for (var i = 1; i <= 100; i += 1)
{
  console.log('for: I IS', i);
}
 
console.log('FOR LOOP IS OVER', i);
 
 
 
 
 
// Collections
//-------------------------------
 
// An array called foods (the name doesn't really matter)
var foods = [ 'pizza', 'cookies', 'bread' ];
 
// Declare a function that will do something with a single food
function printFoodsOrWhatever (item) {
    console.log(item);
}
 
// Pass in the function to the array's .forEach method
foods.forEach(printFoodsOrWhatever);
 
 
// You can also just send a function directly
// foods.forEach(function (item) {
//     console.log(item);
// });
 
 
// Map
 
var foods = [ 'pizza', 'cookies', 'bread' ];
 
var capsFoods = foods.map(function (food) {
    return food.toUpperCase() + '!!!!';
});
 
console.log(capsFoods);
 
 
// Reduce
 
function ander (pre, food) {
    return pre + ' AND ' + food;
}
 
var msg = foods.reduce(ander, 'I LIKE: asparagus');
 
console.log(msg);
 
 
 
// Objects (a.k.a. hashes)
//-------------------------------
 
var obj = {
  food: 'pizza',
  amount: 9999,
  'key-with-hyphens': 'HYPHEN VALUE',
  with_underscores: 'this is an underscore key',
  food: 'cookies'
};
 
var someVariable = 'amount';
 
console.log(obj);
 
console.log("obj[someVariable] =", obj[someVariable]);
console.log("obj['food'] = ", obj['food']);
console.log("obj.food = ", obj.food);
console.log("obj['key-with-hyphens'] =", obj['key-with-hyphens']);
console.log("obj.with_underscores =", obj.with_underscores);
 
 
 
// By the way... the objects we use for hashes can also double as instances
var cart = {
  items: [],
  add: function (item) {
    if (item === 'drugs') {
      console.log('GET OUTTA HERE');
      console.log('(call me later if you are going to party)');
    } else {
      this.items.push(item);
    }
  }
};
 
 
cart.add('cookes');
cart.add('bananas');
cart.add('drugs');
 
console.log(cart);

/* command d 
to select next change two at the same time


each
doesn't return new value

map 
return new value

reduce 
take a array and convert into a single value

filter
same as .select ruby 

name classes
js-
js-pizza 

data-hook
data-button */