Sunday, November 22, 2015

Angular, The Portal To Another World


You know that portal that opens up in 85% of modern SciFi TV shows... the one where you jump into it in one place and are spat out somewhere very far from there, well Angular JS is like that, but instead of connecting one geographic location to another, it connects a place on your HTML file to a place on your JS file.

SETTING UP ANGULAR: 
In order to use Angular, when you set up your HTML, you should script Angular into the head of the HTML doc, above your custom JS script tag.

NG-APP
You then need to insert an ng-app into your page. You can choose to use Angular in your entire page, or just a portion of it. If you would like to use it in the entire page, type ng-app= "NAMEoFaPP" inside the HTML tag.


If you would like Angular to apply later on in your page then enclose the ng-app... inside the div containing the region of your page where you would like to use angular.

On your main JS you need to define your module (app) by  passing a name as its first argument and a blank array -- or an array containing any additional dependencies you would like to make use of in your app eg other modules you want to have access to within this app).

EMBEDDED APPS/ CONTROLLERS:
The next step is to set up an embedded app and/or a controller to specify the content and functions that you want to use in a given region of your page. You can set up a run function and reference the "view" (ie rendered html) by referencing the $rootScope. Anything contained within the html (or whichever tag you put your ng-app), is contained within the rootScope.

To delegate control over specific regions of your page, you must set up controllers. Controllers can access the view region of the page where they are named as controller, by referencing $scope.VariableToBeUsedInThatRegion.

Within the controller you can define functions that you will be able to employ and reference in the HTML.

MODELS AND PORTALS
To plug data from the main JS directly into a region of the page that is controlled by a particular controller, you can set up an element as an ng-model and name a variable to correspond to that model (so that you can reference the element from inside the controller in your JS file which contains that model ) And you can also reference declared models within the HTML itself by using double curly braces to surround the name of the model you are referencing: {{person.name}} ***Note you can only plug in strings here.

The best demonstration of the Science-Fantasy-Awesomeness of Angular is setting up double-data-binding (you can also set up triple-data-binding if you are connecting your app to a real-time server (eg firebase)... but before we can think about tying up a third data source and bringing her into bed, lets get a two way hook up going.

To bind data two ways just have your main JS reference the variable for your model in the scope... and watch the magic happen:





You can change text on one part of your page, while typing in another part of your page... and at the same time you are also changing the value on your js page as well... just like that.

To learn more about the crazy awesome power of Angular... read the AngularJS Docs, or do a tutorial.

Saturday, November 14, 2015

Little Homepage on the Web Search Query


Ever since the first time my mom read me Little House on the Prairie, I've wanted to build my own home. A log cabin with a fire place and a vegetable garden... I wanted a simple life where I could plant carrots, milk my goat and churn some mother fuckin' butter.

But the older I get, the more I wonder if I'll ever get a chance to build my tounge-in-groove, secret-passage-between-the-walls-that-leads-down-to-the-sex-dungeon, chicken-coop-havin' dream home. Fuck-it though, Imma keep saving up for a plot of land and some live stock, but in the mean time , just on the off chance that the physical house doesn't happen, I'm going to build a website...a simple webiste... about building a house... and I'm going to make it from bare HTML up...

These are the materials I will be working with:
HTML -the frame that supports casa de website. Throughout the page there are elements enclosed in tags in which you can enclose text, images, video etc. CSS adds personal flare to your site. You can need to link your HTML file to a CSS file to control the way elements are styled. CSS can change everything from text color and size to alignment of objects and opacity. CSS is important to make a website presentable, but it is not required. You can still run a website without CSS. If you want to make your website dynamic and/or interactive, you need to link it to a javascript file. Javascript is like the running water, heater, and electricity. With Javascript you can animate, re-style and personalize your site for every user.

Step 0: Download a text editor and emmet.io It is not necessary, strictly speaking, to have a special text editor to build a web site. Any plain text editor (note pad, text edit etc) can assign a file a .html,  .css or .js file extension which is all that is necessary for a browser to identify that the file contains code. However, a text editor is like the power tools of web developing... you can get by with a hammer and nails, but you probably aren't going to get around to building a sex dungeon without at least a power drill.  Text editors  greatly help with formatting and alerting you of syntactical errors (such as open parenthesis, missed commas etc). I use sublime which is free (though occasionally you do get pop ups -- which you can ignore, imploring you to purchase the official version of Sublime... its the same in every way except you wont get pop ups any more). Emmet is that guy down the street that works construction and has his own bob cat that he'll bring over to help you trench out your foundation... ie takes the ease and error prevention of text editors one step further by allowing you to abbreviate tags, assignment of classes etc. I highly recommend you download and learn the basics of emmet.


Step 1: layout HTML:
   I want to have a site where I can drag slices of a picture of a cabin onto a mat that will grab them when I drag them over it. I sliced my picture into 4 pieces, but I will want to keep them all together when you first open the site, so I put all the slices of the image in to a div. I have another div that will be the drop target for the pictures and then I wrapped the entire page in a div so I can keep everything aligned the way I like.



Step 2:
set up some CSS
There are many templates, libraries and other resources to do the brunt work of CSS and make alignment etc much easier for your page. A couple popular ones are Bootstrap and foundation both of these require that you have jQuery scripted to your page, but my page is very simple so I am not using anything beyond basic CSS.


Step 3:
JavaScript

Drag and drop are features of the jQuery ui library. The only coding necessary to drag and drop elements is the jQuery to identify what is draggable and what is droppable and specify the behavior you would like upon dropping the element.


step 4: going live
1. create a git repository for your files.
2. make sure that all your files are saved.
3. create a new git branch called gh-pages (git checkout -b gh-pages)
4. push to your gh-page (git push origin gh-pages)
5. go to your git hub page -to the settings for your repository and find the url for your new website

checkout Github and read up on my blog about git hub.

Finished product

Below are some resources to learn more about HTML, CSS, JavaScript, jQuery: https://jquery.com/
Code School jQuery, Code Academy jQUery,  W3Schools HTML/CSS, Code Academy HTML/CSS, Code School HTML / CSS, Official MDN Javascript docs, W3Schools Javascript, Code School Javascript 

Monday, November 9, 2015

Teaching a New Browser Old Tricks

Up until today every time I pulled input from a user that input would only exist as long as the page was not refreshed.As soon I clicked the refresh button my code would swirl down into the sewer of code of unsaved data that exists in the DOM.

My mind was blown last week when i learned about the wizardry that is session storage and local storage. Your browser can remember data from refreshes and even browser accesses past.

WHAT IS SESSION STORAGE?
Each website has its own storage space where you can save information that you will need access for longer than just one refresh of the page. When you save data as session storage it persists (remains in storage) until you close the browser tab or window. (It will not be passed on to new tabs or windows). Once you close the tab it is deleted.

This might be useful for a simple game where you have a limited number of tries at a task and wanted to be able to refresh the page to set you back to the previous try or close the tab to entirely restart. It may also be helpful for a survey or other nonsensitive document, where you want to be able to keep the info you've already filled out and saved, but clear the rest with a refresh.

syntax for saving to session storage:
sessionStorage.variable = value;
(the value can be a number, string, array, or object that has been converted into a string).
to remove an item from session storage:
sessionStorage.removeItem("name of session Storage variable you want to remove");
to clear all out of local storage:
window.sessionStorage.clear();


to view session storage: 
in Chrome dev tools you can view what is stored in your session storage by going to the resources tab  at the top of the tools and then when you're in the resources tab, on the left side select Session Storage and you should be able to see the variables (keys) and their values that are being stored.



WHAT IS LOCAL STORAGE?
Local storage works much the same as session storage, except that data saved in localStorage persists until it is removed , either through dev tools console or through a script that is being run on the page. (ie closing tabs, refreshing browser, shutting down computer etc will not remove it, the browser must be told to remove the data.) Below the two variables test 1 were assigned. Once the browser was closed and reopened the local storage variable persisted, but the sessionStorage was cleared.




to view session storage: in Chrome dev tools you can view what is stored in your session storage by going to the resources tab  at the top of the tools and then when you're in the resources tab, on the left side select Session Storage and you should be able to see the variables (keys) and their values that are being stored.









JSON
*** Local storage and Session storage store all data as a string ***

So if you save a number to local storage it will be converted into a string, so if you were to try to add it to another number it would concatenate the string instead of actually preforming math...



the solution to this is to use JSON.stringify to convert the data into a string before you save it  and then use JSON.parse to convert it back to its original format so that you can work with it. (if you are only saving a single string, it is sufficient to just put the string in quotes without bringin JSON into it.

NOTE: you cannot stringify a function.

read more about JSON.

GET YOUR HANDS DIRTY:
-try this go to your browser and open the dev tools on an empty page and type localStorage.bgColor = "red."
-Then refresh the page and type localStorage.bgColor ... it will console log red... because it remembers.
-Now that variable bg.Color will be red until it is changed manually OR until code for that page is run that changes it.
- If you link a javascript file to your index page and just type:
document.body.style.backgroundColor = localStorage.bgColor;
then refresh your browser, BAM! Your page is now a sexy fire engine red. 

Sunday, November 8, 2015

Let Me Re Iterator That


Iterators are handy tools that make looping through an array of data quicker than traditional for or while loops. The javascript iterators, map, reduce and forEach all employ an anonymous function that has three arguments built in: item, index and all.

Item references the current item in the array being operated on.

Index is the index of the item in the array that is being iterated through. (eg the first item in the array would have an index of 0).

All is the array itself.

MAP.map will go through every item in an array, preform some code on it and return a new array of THE EXACT SAME SIZE.

syntax:

var mappedArray= array.map(function(item, index, all){

   preform some operation to every item in array and return a new array with every item as the item       has been transformed by your code.

  return item OR all OR a variable you create or whatever.
})

You must always write a return statement at the bottom of your array (or else it will just be an empty array).

Examples of when to use this:
if you have a string of text and you want to manipulate each word or each letter (eg change certain letters to caps or if you want to add a certain number to each existing number in an array of numbers.

example: 
Johnny is making a database to keep track of each of the gentleman callers that visit his mom late at night. He wants to be able to add information to their profiles as he gets to know them better. Recently he found out that his mom only dates guys that are 27 years old, so he writes the following program.

var momsHarem = [{Name: Bruce, VisitsOn: [Wed]}, {Name: Clark, VisitsOn: [Wed,Friday]}, {Name: Tony, VisitsOn: []}]

function addToHarem(array) {
var newArray = array.map(function(item, index, all){
   item.age = 27;
console.log(item);
       
      return item;
 
})
  return newArray
}
addToHarem(momsHarem)

FOR EACH.forEach will go through every element in an array and will allow you to present some condition or not that will affect which items in the array are manipulated. If you want an array of the exact same size it is probably better to just use map, but for each can also be used.

syntax: 

array.forEach(function(item, index, all){

if (item MEETS SOME CONDITION) {

preform some code on the item and or index or whatever
}
  manipulatedArray.push
 OR
 $("#id").text(manipulated item from array)
OR
whatever else you wanna do
 })

example: 
Abhi has an extensive library of  things that sparkle, so he keeps the information about the items in a database. He wants to be able to search for particular theme or title and have the results returned in an array, so he writes the following function:
thingsThatSparkle = [{item: "glitter", location: "lv69", subGenres: "crafts shimmer"}, {item: "new penny", location: "fm11", subGenres: "coin glint"} ]

function findShinys(array, value){
  var results =[]

  thingsThatSparkle.forEach(function(item, index, all){
  var keyValue = item.subGenres
console.log(keyValue)
   if ( keyValue.indexOf(value) > -1) {
       results.push(item)
    }
  })
  return results;
}
console.log(findShinys(thingsThatSparkle, "glint"))

findUserInfo("a", array)

forEach does not return a value so to get info out you will need to push to an array or print to document or something along those lines to have the results of the loop show up.

when to use it:
if you want to do something to eliminate the odd numbers from an array OR send just the first 3 items to an array and do nothing with or do something else with the rest of the items. OR add a class to only the items that contain the letter B or whatever it is that you want to sort out one thing from another or eliminate items from an array.

REDUCE
.reduce will go through each item in an array and return a single value. So if you want to take an array of letters and return a single item rather than an array. Reduce also has an additional argument in front of these three, accumulation, which is the accumulation, running total of numbers being operated on or the current version of the string. The initial value of the accumulation can be set as a second argument in the anonymous function.

syntax:

var reducedValue = array.reduce(function(accumulation,  item, index, all){
   acc = acc item OPERATION (+, -, *, / etc...)
}, STARTING VALUE FOR THE ACCUMULATION -- USUALLY 0 OR 1 DEPENDING ON THE OPERATION YOU ARE PREFORMING)

WHEN TO USE
if you want to take an array of numbers that have been input and preform the same operation on them (eg if you wanted to add all the elements in an array and then work with the total)

OR

If you have a multidimensional array of letters or numbers and you want to concatenate each array within the array into a single value and then do something with that single value.

example:
Sally is building an app that pushes the value for the number of shits she gave in each of her classes today. She wants to take that data and total it so she knows the total amount of shits she gave all day long.

var shitsGivenToday= [0,1,0.5,2.4,0 ]

var totalShits = shitsGivenToday.reduce(function(acc, item, index, all){
   varShitsGivenToday = acc + item;
  return acc;
},0)

more about iterators

My friend DOM

Way back... a few months ago, when I started interviewing for coding bootcamps, one of my interviewers asked me to tell him about the DOM... and I was like, "Sorry I don't know him. Is he like to Fonz of programming..." He's not. In fact he's not a he at all.

WHAT IS "THE DOM"?
DOM is an acronym that stands for Document Object Model and it's basically a copy of the HTML that your browser renders when you open it.

WHY DO YOU NEED A COPY OF WHAT YOU WROTE?
Because it is a copy multiple users can reach out to the page without having to have the source files on their computer and they can interface with the same page at once and have a user experience that is unique from that of others.

DOM MANIPULATION:You don't want to access the DOM much. The more you grab info or push info to the DOM the slower your program will run. (because you have to wait for the script running the program to reach out to the DOM. Manipulating things in your actual script first and then sending as much correspondence to the DOM at once as you can is the preferred way to do things.

JQUERY SELECTORS AND THE DOM
Jquery makes interacting with the DOM much easier than using vanilla (plain ol') java script. The selectors allow you to easily classify and reference page elements like buttons, input and divs, text etc. The best way to learn about jQuery is to read the  jQuery docs, but the TLDR is that it is a library that has converted the long hand and sometimes confusing process of referencing the DOM with javascript into simple procedural steps. Once you add a script tag for jQuery (eg <script src="https://code.jquery.com/jquery-2.1.4.min.js"></> ) your browser will know to reference that library every time you include an $ symbol before your text. For example, $("#name") is the jQuery way to refer to an element on your DOM that has an id of name.

There are tons of handy things that can be with jQuery, so I definitely recommend having a peruse through the jQuery site.