Exercise: Midterm Prep Puzzle

In the following pen, you will need to add the correct class from the pre-defined classes inside the correct elements.

CodePen Link

Basically, look at the available classes, for example

This would be the styling that we would want to apply to the header of our website. In the html, the following element appears to be the correct header that needs this styling:

So we would add the class two to it like this:

And our preview will now look like this:

One class may be used many times, and some elements may not need a class at all!

Preparing for the Midterm Retake – Building website from scratch

Building a simple website from scratch

In this tutorial we’ll build the exact same website from the midterm. It contains the following elements:

  1. Header: With a logo and a menu
    1. The menu should have black buttons with white text
  2. A two column main element
    1. The left column should have a title and a vertical navigation
    2. The right column should contain a title and a paragraph of text

The final product should look like this:

Creating a project inside WebStorm

You can either create a project from the welcome screen

Or if you’re already inside a project go to File -> New -> Project

Replace where it says “untitled” with your project name

like this

No spaces! Just text characters.

Then click the create button.

Starting our project with the needed files

We’ll first need our index.html as this is the file our server will always look for to show to the user first (even if you have 100 other pages).

Right click on the little folder with the name you chose for the project, then select New -> HTML File

You should now see an index.html in the left column of your editor

Now we repeat the process to create a stylesheet called style.css (please always use lowercase characters, no spaces, and try to name the files for each website the same! For example, your stylesheet can be named main.css or style.css, but those are really the only names you should use!)

Adding your stylesheet in the HTML

For us to use a stylesheet (as there can be 10 available stylesheets in a big project for each page) we need to link it from the html file using the link tag.

The link tag should go immediately before the closing of the head tag.

It contains two attributes, rel (relationship, it’s a stylesheet) and href (which is the path to the stylesheet file).

If we created a folder called css then the href would be href=”css/style.css” meaning we’re referencing the folder and then the file inside it.

As a sanity check, making sure our stylesheet is now linked we can simply make the body background black. When we preview our html page the background should be black.

And then from within our index.html file we click the browser icon from the top right:

Great, we’re all set here, let’s erase the sanity code from style.css.

To make it easier to look at both our html and css at the same time, you can simply right click on the style.css tab in your editor and choose split vertically

Then close the tab on the left side that says style.css leaving it only on the right-hand side.

 

Adding the initial HTML markup

The very first thing we should tackle is each section of our website. In this case, we’re creating a simple website with two sections, a header and a main (which has the two columns).

Keeping in mind all our code goes inside the body element! We use a class to identify each section, allowing us to reference them later when we apply styling.

Filling in the sections

Now we can start filling in each section with markup based on our website design. In the header, we have a logo and a menu. The menu contains buttons (anchor links).

And the main section contains two columns:

Each column has a title

In the left column we add a vertical menu, and in the right a simple paragraph.

Here is the final code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="header">
        <h1 class="logo">
            Logo
        </h1>

        <div class="menu">
            <a href="https://google.com">
                Go To Google
            </a>
            <a href="https://microsoft.com">
                Go To Microsoft
            </a>
        </div>
    </div>

    <div class="main">
        <div class="left-col">
            <h2>Welcome</h2>
            <div class="left-menu">
                <a href="https://google.com">
                    Go To Google
                </a>
                <a href="https://microsoft.com">
                    Go To Microsoft
                </a>
            </div>
        </div>
        <div class="right-col">
            <h2>Great stuff</h2>
            <p>Right column text</p>
        </div>
    </div>
</body>
</html>

Adding our styling

To make our webpage look the same in every browser we can include the normalize.css library. We add it the same way we add our style.css, with a link tag, but we can use a CDN link instead of storing it in our project folder.

Very important to notice that we add the link tag before our style.css, this ensures our styles override those of the normalize.css! This is the same logic as when we add a framework. Styles declared lowed in the document are more important.

Now we can focus on getting the website to look correctly. I will again do this section by section. Starting with the header.

The header contains two immediate children, .logo and .menu which should appear next to each other as columns. To do this we’ll apply:

  1. display: flex; // making its immediate children display as columns
  2. justify-content: space-between; // forcing the columns to spread out to each side of the page adding space between them
  3. align-items: center; // now we can center the items inside vertically, because our logo will be much higher than the menu items and we want it to look nice

Which will look like this:

Converting Anchor Links into Buttons

To make our navigational links appear as buttons (larger clickable area, custom colors, etc) we have to select the actual anchor tag with our CSS. Otherwise the browser will always apply its own styling that we can’t override.

Here is how we select the anchors inside the .menu div:

By selecting .menu div first, then adding a space, and then entering the name of the anchor tag a, we are telling the browser to select all anchor elements inside the div with a class menu.

Allowing us to apply the following important styles:

  1. display: inline-block; // By default an anchor is display inline, which is great when it appears amonst text. But as a button it needs to be able to display as a button with extra padding inside it. To do this we use inline-block
  2. text-decoration: none; // The browser adds an underline to all links, so we need to remove this (if we want)
  3. padding: 10px 20px; // Padding should typically be less on top and bottom than left and right. So we set top/bottom to 10px and left/right to 20px. We use padding on the anchor because we want the clickable area to be nice and large. If we used margin, or added padding to the wrapping element, the clickable area would only be the text of the anchor
  4. color: white; // Changing the text color
  5. background: black; // Changing the background color

Let’s review what we have so far:

Great, the header is in great shape. Let’s move to the .main element with the two columns. Step 1, make the immediate children display as columns:

Now we need to add styling to the buttons in the left column navigation, almost identical to the ones in the header, but I want the buttons to be display block, which will make them take up the full horizontal space in the left column. And add some spacing underneath with margin-bottom:

Result

Looking great, a couple more small styling improvements and we’re done.

Adding padding to our columns

We don’t want the right column to be directly touching the left column, so we can simply add some padding to the columns to give them a little breathing room:

Here we use a special css selector, by declaring each selector and then adding a comma between the next selector we can select multiple selectors and apply the same styling. So we’ll add 15px padding to the left column, right column, and the header. Result will look like this:

And now we just want to add a gray background to the left column:

Here is the final CSS code:

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.menu a {
    display: inline-block;
    text-decoration: none;
    padding: 10px 20px;
    color: white;
    background: black;
}

.main {
    display: flex;
}

.left-menu a {
    display: block;
    margin-bottom: 3px;
    text-decoration: none;
    padding: 10px 20px;
    color: white;
    background: black;
}

.left-col, .right-col, .header {
    padding: 15px;
}

.left-col {
    background: gray;
}

 

That’s it! You’ve created a basic website 🙂

jQuery Exercises

Contact Form with PHP/ReCaptcha

A great script I bought here

https://codecanyon.net/item/contactme-responsive-ajax-contact-form-html5-php/20256608

You can download from here.

After download, I had to change the following fields:

  1. from_name
  2. from_address
  3. to_address

If you want to enable human validation (prevent bots from submitting) there are instructions in index.html you can follow.

Visit https://www.google.com/recaptcha/admin

Fill out the following items

It will provide you with all the needed info here

Update the configs.php file

Change the html as needed to enter the sitekey (this occurs for each form on index.html so you need to copy paste a few times)

Uncomment script near the bottom of the page!

You end up with

Which submits and sends an email like this!

Pretty awesome! Check out final product http://myfinalprojectrocks.com/contact/

The Ultimate JavaScript Introduction

Variables

Variables are containers that you can store values in. You start by declaring a variable with the var keyword, followed by any name you want to call it:

var myVariable;

A semicolon at the end of a line indicates where a statement ends;

String

We indicate a string by surrounding the string value with quotes, like this:

var variableName = "string content in here";

Now you try it!

See the Pen JS-Intro by Angel Grablev (@agrublev) on CodePen.0

  • Number – 1, 5200, 95.34
  • Boolean – true/false
  • Array – store a list
    • var myArray = [1,2,3,4,5];
    • Accessing a list
    • var myArr = [1,2,3,4];
      myArr[0]; // returns 1 because arrays start from 0
    • Looping lists
    • var myArr = [1,2,3,4];
      // Using jQuery! As it's much simpler/prettier
      $.each(myArr, function( index, value ) {
        console.log( index + ": " + value );
      });
      // will return
      // 0: 1
      // 1: 2
      // 2: 3
      // 3: 4
    • Push unshift splice
    • var myVar = [1,2,3,4];
      // add to end of array
      myVar.push(5);
      console.log(myVar);
      // [1,2,3,4,5]
      
      // add to beginning of array
      myVar.unshift(0);
      console.log(myVar);
      // [0,1,2,3,4,5]
      
      // remove 1 item at index 0
      myVar.splice(0,1);
      console.log(myVar);
      // [1,2,3,4,5]
  • Object – store name: value properties
    • Accessing objects [] vs .
    • Looping object (no order!!)
    • Adding/removing properties
    • // empty object
      var myVar = {};
      console.log(myVar);
      // {}
      
      // predefined object
      var myVar2 = {
          // property
          "name":"value"
      }
      console.log(myVar2);
      // {"name":"value"}
      
      // predefined object
      var myVar3 = {
          "firstName":"Angel"
      }
      // safer way to get the value of a property
      console.log(myVar3["firstName"]); // Angel
      console.log(myVar3.firstName); // Angel
      // adding a new property to an existing object
      myVar3.lastName = "Grablev";
      console.log(myVar3.lastName); // Grablev
      
      console.log(myVar3); // {"firstName":"Angel","lastName":"Grablev"}
      // removing a property
      delete myVar3.lastName;
      console.log(myVar3); // {"firstName":"Angel"}
      
      
      // looping is similar to array, but instead of the index we get the name
      // this loops follows NO ORDER!
      $.each(myVar3, function( propertyName, propertyValue ) {
        console.log( propertyName + ": " + propertyValue );
      });
      // firstName: Angel
      // lastName: Grablev

Functions

Are a way to set blocks of executable code that can be called later as many times as needed. You can set a name for the function and set parameters to be passed into it.

function add(x, y) {
  // can return a value, but it's not required
  return x + y;
}
console.log(add(1,1)); // 2

var aNumber = 0;
function addToNumber(x) {
  aNumber = aNumber + x;
}
addToNumber(5);
console.log(aNumber); // 5
addToNumber(5);
console.log(aNumber); // 10

See the Pen JS-Intro by Angel Grablev (@agrublev) on CodePen.0

To execute a function we simply use its name and pass any needed parameters inside the parenthesis. If no parameters then simply adding parenthesis executes the function.

function loveIt() {
    console.log("Love it");
}

loveIt(); // Love it

Anonymous functions

An anonymous function has no name and is always executed right away. Most commonly we pass an anonymous function to libraries like jQuery so it knows what code to execute for us.

// Passing anonymous function to jQuery to do something
// on click
$("#click").on("click",function(){
    $("#click").addClass("clicked");
});

// Can be done just as easily with a named function like this
function whenClicked() {
    $("#click2").addClass("clicked");
}
// jQuery will simply execute the function
$("#click2").on("click",whenClicked);

Storing function in a variable

We can store a function in a variable, which does almost the same thing as a normal function declaration.

function add(x,y) {
    return x+y;
}
// is identical to
var add = function(x,y) {
    return x+y;
}
// we're simply storing an anonymous function
// inside our add variable

Comparisons and if statements

// 3 = signs means absolute comparison
console.log("1" === 1); // false - string is not number

// 2 = signs means relative comparison
console.log("1" == 1); // true - they are relatively the same

// < less than | <= less than or equal to | > and >= same but opposite
console.log(0 < 1); // true
console.log(1 <= 1); // true

// && says "and" meaning both must be true 
// || says "or" means either must be true
console.log(0 < 1 && 1 < 1); // false
console.log(0 < 1 || 1 < 1); // true

If statements

var name = "angel";
if ( name === "angel" ) {
    // yep
} else {
    // nope
}

Variable scopes!

Every variable we define exists in a scope. We can only call variables from parent scopes.

// window scope - think of it as browser wide
var parent = "Im at top";

function child() {
    var child1 = "I'm inside child!";
    console.log(parent); // Im at top
}
console.log(child1); // undefined - IT DOES NOT exist in this scope

// Also you can't use variable/function before it's defined
test(); // error
function test() {
    console.log("Will NOT be executed!");
};

Brain teasers

var a = 1;
var b = 2;

(function() {
  var b = 3;
  a += b;
})();

a; // What's a?
b; // What's b?
function parentFunc() {
    var a = 1;
    function nestedFunc() {
        var b = 4; // parentFunc can't use this

        return a + b;
    }
    return nestedFunc(); // what's returned?
}
function createAdder(x){
    return function(b) {
        return x+b;
    }
}
var adder1 = createAdder(5);
console.log(adder1(1)); // what's the result?

 

Useful snippets

Adding jQuery to your website

  <!-- add jquery right before the ending body tag -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <!-- make sure to add your JS after jQuery otherwise you can't use it -->
  <script src="js/main.js"></script>
</body>

Using jQuery

// This is jQueries way of waiting for page to load
// we simply pass an anonymous function to the jQuery function
$(function(){
    
});

// Basically equiavelnt of this
var $ = function(runThisCodeWhenPageLoaded) {
    // some magic happens and then it calls your annonymous function
    runThisCodeWhenPageLoaded();
};
// Then you'd call it as usual
$(function(){
    console.log("TEST!"); // TEST!
});

Common jQuery usecases

// Handle a click on element with class .some-element
$(".some-element").on("click",function(){
    // do something
});

// Handle a click on an anchor with href="#"
// without moving to top of page
$(".button a").on("click",function(browserEvent){
    // take the browser event and prevent the default reaction
    browserEvent.preventDefault();
    // do something
});

// Handle a click on element with class .some-element
// and since you can have 100 elements with that class
// we can reference the exact one we clicked with $(this)
$(".some-element").on("click",function(){
    $(this).hide(); // will ONLY hide the clicked element
});

// Common interactions with elements

// <div class="some-element"
// becomes <div class="some-element test"
$(".some-element").addClass("test");

// hide/show the element
$(".some-element").hide();
$(".some-element").show();
// if an element has display:none; css applied
// or it was hidden with jQuery you can show it
$(".some-element").fadeIn(3000); // fades it in in 3seconds
$(".some-element").fadeOut(5000); // fades it out in 5seconds

// find a child
$(".some-element").find(".test"); // finds a child of .some-element with class .test
$(".some-element").find(".test").hide(); // hides the child .test

// find a parent of the element
// <div class="test">
//		<div class="doesnmatter">
//			<a href="#" class=".some-element">ME!</a>
$(".some-element").parents(".test"); // finds the first parent of .some-element with class .test
$(".some-element").parents(".test").hide(); // hides the child .test

// Adds an element inside and at the end of the chosen element
$(".inside-me").append("<div class='test'>Awesome</div>");
/*
<div class="inside-me">
    <div class="random">
        Random element
    </div>
    <!-- WE ADD THE DIV CLASS TEST HERE -->
</div>
*/

// Adds an element after the chosen element
$(".inside-me").after("<div class='test'>Awesome</div>");
/*
<div class="inside-me">
    <div class="random">
        Random element
    </div>
</div>
<!-- WE ADD THE DIV CLASS TEST HERE -->
*/

 

Setting up Firebase

Go to https://firebase.google.com/ and click SIGN IN

Then go to https://console.firebase.google.com/u/0/ and click Add Project

Enter a name and Create Project

Navigate to DEVELOP -> Authentication then click Set Up Sign In Method

Enable the ones you want to use

Remember that later you will need to add the domain of your website so it works!

Now select DEVELOP->Database

Then Firestore Get Started

Set it in Test Mode and Enable

Finally, let’s enable storage

Now go to rules tab

Change to

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write
    }
  }
}

Then publish.

 

Get authnetication information

Click the COG on top right and select project settings

Now select

This will give you the code you need to add inside your project!

 

Download the example zip and then follow these steps:

  1. Extract zip
  2. Open the file js/initializeFirebase.js
  3. Replace its contents with the settings from above
  4. Open terminal and type “npm install”
  5. Every time you want to run the system type “gulp”
  6. Here are the links you can go to for the different examples
    1. will have a full login/signup and list items example
    2. /items.html will have a full example for working with items (add/edit/delete)
    3. /upload.html has an example of uploading files
    4. /auth.html has an example for sign up and login

https://angelprivate.s3.amazonaws.com/teaching/additionalFun.zip