Author: agrublev

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.32466

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:

And watch this video:

TO BE ADDED LATER (IGNORE):

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

Setting up Visual Studio Code

For students who already set up visual studio scroll to the bottom of this post!

Watch the video here if you need visual instructions https://my.pcloud.com/publink/show?code=XZYzg97ZUQI88fjJP3HSQlYxyr2rzFRMbTqk

The first thing you need to do is download the application from the following link:

https://code.visualstudio.com/download

After you install the app by dragging it into the Applications folder, open it.

Now navigate to this link to install the Settings Sync extension https://marketplace.visualstudio.com/items?itemName=Shan.code-settings-sync  and click the Install button

Once you install the extension you will need to click the Reload to Activate button

Once the app reloads follow these steps:

  1. Use keyboard shortcut Cmd + Shift + P to open the command palette
  2. Type Sync and go down with the arrow keys to the Sync: Advanced Options and click Enter
  3. Use arrow keys to go down to Sync: Download Settings from Public GIST and click Enter
  4. Use keyboard shortcut Cmd + Shift + P to open the command palette again
  5. Type Sync: and go down to Sync: Download Settings then click Enter
  6. It should ask you to enter a GIST ID enter the following 846a59831c3a903c311ea25354694cae

It will take a few minutes for all the Extensions to load, once they are done it will ask you to reload. Reload and you are done!

Already followed this guide and just need to update:

  1. Type Cmd + Shift + P and type “Download” find/select “Sync: Download Settings
  2. A popup will ask you to reload click Yes

Suggested extensions:

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 🙂