• Home

Category: Exercises

Learn Programming / JavaScript Basics

The “script” tag

JavaScript programs can be inserted into any part of an HTML document with the help of the <script> tag.

For instance:

<!DOCTYPE HTML>
<html>

<body>

  <p>Before the script...</p>

  <script>
    alert( 'Hello, world!' );
  </script>

  <p>...After the script.</p>

</body>

</html>
alert("Thanks for your input!");

Let’s say my name is Mark, and I want to store this information in the browser.

A variable is created when you write var (for variable) followed by the name that you choose to give it. It takes on a particular value when you assign the value to it. This is a JavaScript statement that creates the variable name and assigns the value “Mark” to it

var name = "Mark";

Now the variable name refers to the text string “Mark”. Note that it was my choice to call it name. I could have called it myName, xyz, lol, or something else. It’s up to me how to name my variables, within limits.

name refers to “Mark”. Then I come along and code the line…

name = "Ace";

Before I coded the new line, if I asked JavaScript to print name, it printed… Mark But that was then. Now if I ask JavaScript to print name, it prints… Ace

Alerting the name variable!

alert(name);

What do the quotes mean, and what happens if I omit the quotes? The syntactic difference between variables and text strings is that variables are never enclosed in quotes, and text strings are always enclosed in quotes.

A string isn’t the only thing you can assign to a variable. You can also assign a number.

var weight = 150;

Having coded the statement above, whenever you write weight in your code, JavaScript knows you mean 150. You can use this variable in math calculations. If you ask JavaScript to add 25 to weight…

var newWeight = weight + 25;
alert(newWeight); // will say 175

JavaScript can also handle an expression made up of nothing but variables. For example

var originalNum = 23;
var numToBeAdded = 7; 
var newNum = originalNum + numToBeAdded; // newNum equals 30

Working with strings

suppose you wanted to personalize a message. In another part of your code you’ve asked the user for her name and assigned the name that she entered to a variable, userName. (You don’t know how to do this yet. You’ll learn how in a subsequent chapter.) Now, you want to combine her name with a standard “Thanks” to produce an alert that says, for example, “Thanks, Susan!” When the user-provided her name, we assigned it to the variable userName. This is the code.

alert("Thanks, " + userName + "!");

Using the plus operator, the code combines—concatenates—three elements into the message: the string “Thanks, ” plus the string represented by the variable userName plus the string “!” Note that the first string includes a space. Without it, the alert would read, “Thanks,Susan!”. You can concatenate any combination of strings and variables, or all strings or all variables. For example, I can rewrite the last example this way

var message = "Thanks, ";
var banger = "!";
alert(message + userName + banger);

Trick question:

What will be alerted here

alert("2"+"2");

Now you try it:

TIP: Use this link http://x.co/jslinks to automatically open all the following items in new tabs

Prompts

var spec = prompt("Ask some question?", "default value?");

Prompt code is like alert code, with two differences.

  • In a prompt, you need a way to capture the user’s response. That means you need to start
    by declaring a variable, followed by an equal sign.
  • In a prompt, you can specify a second string. This is the default response that appears in
    the field when the prompt displays. If the user leaves the default response as-is and just
    clicks OK, the default response is assigned to the variable. It’s up to you whether you
    include a default response.

As you might expect, you can assign the strings to variables, then specify the variables
instead of strings inside the parentheses.

var question = "Your species?";
var defaultAnswer = "human";
var spec = prompt(question, defaultAnswer);

The user’s response is a text string. Even if the response is a number, it comes back as a
string. For example, consider this code.

var numberOfCats = prompt("How many cats?"); //enter 5
var tooManyCats = numberOfCats + 1; // will get 51

To fix this problem we can use a JS helper function called parseInt, which takes a string and tries to figure out what the number would be inside the string

var numberOfCats = prompt("How many cats?"); //enter 5
var tooManyCats = parseInt(numberOfCats) + 1; // will get 6

If Statements

Suppose you code a prompt that asks, “Where does the Pope live?” If the user answers correctly, you display an alert congratulating him. This is the code.

var x = prompt("Where does the Pope live?");
if (x === "Vatican") {
  alert("Correct!");
}

If the user enters “Vatican” in the prompt field, the congratulations alert displays. If he enters something else, nothing happens. (This simplified code doesn’t allow for other correct answers, like “The Vatican.” I don’t want to get into that now.)

So let’s make a trivia game!

var score = 0;

var x = prompt("Where does the Pope live?");
if (x === "Vatican") {
    alert("Correct!");
    score = score + 1;
} 

var z = prompt("Where does Angel live?");
if (z === "Santa Barbara") {
    alert("Correct!");
    score = score + 1;
}

alert("You got a score of: " + score + " out of 2");

What if we want something that DOES NOT equal the other value?

var x = prompt("Where does the Pope live?");

if (x === "Vatican") {
    alert("Correct!");
    score = score + 1;
} 
if (x !== "Vatican") { 
    alert("Sorry incorrect!"); 
} 

So if it !== doesn’t equal we do something else. But typically it’s easier to say “IF this then do that ELSE do the other thing” which looks like this

var x = prompt("Where does the Pope live?");

if (x === "Vatican") {
    alert("Correct!");
    score = score + 1;
} else {
    alert("Sorry incorrect!"); 
} 

That’s much better.

Functions

Sometimes we want to be able to run the same code one or many times, to do this we can store a set of code inside a function and call it at a later time. This also keeps our code organized!

// Create a function
function nameMe() {
    alert("My Name is Angel");
}

// Call the function to run the code inside it
nameMe();

Functions become really useful when you also pass data inside of them with a parameter like so:

// Create a function
function nameMe(name) {
    alert("My Name is " + name);
}

// Call the function to run the code inside it
nameMe("Angel");

You can even pass the value we got from a prompt!

// Create a function
function nameMe(name) {
    alert("My Name is " + name);
}

var setMyName = prompt("What is your name?");
nameMe(setMyName);

Handling a click

The easiest way to handle a click is the use an html attribute called onclick

See the Pen bzGOXa by Angel Grablev (@agrublev) on CodePen.

So we create a div, then simply add the onclick attribute with a value that will call our function when clicked like this:

<div onclick="quiz()">CLICK</div>

<script>
function quiz() {
    var score = 0;

    var x = prompt("Where does the Pope live?");
    if (x === "Vatican") {
        alert("Correct!");
        score = score + 1;
    }

    var z = prompt("Where does Angel live?");
    if (z === "Santa Barbara") {
        alert("Correct!");
        score = score + 1;
    }

    alert("You got a score of: " + score + " out of 2");
}
</script>

And if you have time for fun do this tutorial:

https://www.codeavengers.com/web-development/100#1.1

It provides video guides AND a solution button up to the top right!

Additional exercises/Reading materials

Once you feel comfortable with all that give this article a look:

http://ucsbwebdev.local/index.php/2018/05/12/the-ultimate-javascript-introduction/

And watch this video:

http://ucsbwebdev.local/index.php/2018/05/14/javascript-additional-training-saturday-may-12th-recording/

TO BE ADDED LATER (IGNORE):

https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics

3 Frameworks In Class Exercise

In class framework assignment

Getting a simple website built with 3 frameworks should be a great introduction!

Directions

  • Create a new Visual Studio folder/project
  • Create 4 HTML files
    • index.html
      • Which should only contain 3 links to the other 3 HTML files
    • bootstrap.html
    • bulma.html
    • uikit.html

Bootstrap

https://codepen.io/agrublev/pen/bQmxJw

UIKit

Final look

https://codepen.io/agrublev/pen/vQVVgO?editors=1000

Bulma

The final product should look like this

https://codepen.io/agrublev/pen/XyxxxQ?editors=1100

 

Extra Credit / Additional Practice

Improve the websites as they can all use a container to wrap them at the very least. Also maybe try to get the javascript working? Should be as easy as adding the styling 🙂

The Website Generator

http://webdevninja.surge.sh/#/

Additional CSS topics

 

Css Introduction

Please use the CSS Reference post to help you along!. Let’s start with a div that has some class: Let’s get started with some basics!

See the Pen cssIntro1 by Angel Grablev (@agrublev) on CodePen.

Now do it yourself 😉 Open this CodePen Let’s get fancy Open this CodePen More exercises:

CSS Reference

Let’s start with some sample div that has a class:

<div class="nameOfDiv">
    Some text
</div>

Now in our stylesheet (or in a codepen use the CSS section and enter your CSS code) we select this specific div with the . selector for class:

.nameOfDiv {
   /* We'll enter our declarations here */ 
}

Inside the curly brackets, we can enter a new declaration on each line. Here is a nice overview of the possible properties you can specify:

Declaration key Declaration values Explanation of property
background black, red, orange, pink, tomato, green, white, etc Sets the background color of our element. It takes in a name of a color.
color same as background, a named color Set the text color of the element (all children of the element will inherit this color!)
width % (of the page) or pixels using px. 30% or 300px Sets the horizontal size of our element
height % (of the page) or pixels using px. 30% or 300px Sets the vertical height of our element
padding Preferably use pixels, but can also take in %. 15px Sets the inner padding of an element
margin Preferably use pixels, but can also take in %. 15px Sets the outer margin of an element
display block, inline, inline-block, flex Allows us to choose how we want our element to display on the page. Flex makes all immediate children into columns.

Now let’s combine all these declarations inside our CSS selector:

.nameOfDiv {
    background: orange;
    color: white;
    width: 150px;
    height: 50px;
    padding: 15px;
    margin: 10px;
    display: inline-block;
}

Great, now the result should look like this:

If we simply add a couple more div’s with the same name the result would be:

This is thanks to the power of an inline-block element which gets the benefits of block (padding/margin) and inline by showing multiple elements on the same line!

An alternative way to accomplish the same result without using display inline-block is to use flex. We need to add a parent that wraps the three div’s nameOfDiv and make the parent display flex. Like this:

<div class="flex">
    <div class="nameOfDiv">Some text</div>	
    <div class="nameOfDiv">Some text</div>	
    <div class="nameOfDiv">Some text</div>	
</div>

And the CSS would be:

.flex {
    display: flex;
}
.nameOfDiv {
    background: orange;
    color: white;
    width: 150px;
    height: 50px;
    padding: 15px;
    margin: 10px;
}

Notice that nameOfDiv is no longer display inline-block. However, with the flex parent we still see:

Feel free to play with the flex example here https://codepen.io/agrublev/pen/ZqdGXR

(please wait until class to go through this page!)

In today’s lesson, we will begin to cover the basics of building websites. The first most important building block of a website is the HTML language, which allows us to give the browser instructions to render our website.

Exercise 1: Add some boxes (div tags)

In the below code editor add some div tags, and see your resulting boxes!

See the Pen MakeSomeBoxes by Angel Grablev (@agrublev) on CodePen.

Exercise 2: Add an image

Now let’s utilize the self closing tag for adding an image.

Add the img tag and then add the src attribute with the value “http://x.co/myimg”

See the Pen MakeSomeBoxes by Angel Grablev (@agrublev) on CodePen.

Exercise 3: My webpage

Let’s build a simple website by simply adding a number of div tags with the appropriate class names.

See the Pen MyWebpage by Angel Grablev (@agrublev) on CodePen.

The final result should look like this:

See the Pen MyWebpageFinished by Angel Grablev (@agrublev) on CodePen.

Please sign up for repl by going to this link http://x.co/joinrepl 

There should be one assignment named “Simple Page for yourself” which is due next Tuesday!

Quiz http://x.co/webquiz4

Links

 Homework

  • Get hosting/domain (if you can’t afford it email me and ill provide you a subdomain and FTP to use, I can install WordPress for you)
    • Install WordPress with a theme
    • OR Put your current web code there
    • OR Use canvas code I shared
  • You should have minimal
    • Your home page elements (at least the main ones)
    • One of the pages of your website almost done