Using Javacsript make your static pages interactive.

Recap

So in our last lesson we learned how to add styles to elements in web documents using CSS rules and selectors. You should recall that we looked at the following points, which will be important for our lesson today:

  • Using CSS selectors to select using classes, ids and tag names (.my-class, #md-id and tag respectively).
  • Using CSS rules to add styles to different elements (like color: red;, font-size: 10px and border: 1px solid blue;).

Making pages interactive

So far everything we've seen with HTML and CSS is what we call 'static'. That is to say, we're simply showing text or information on the screen without any interaction or input from the user.

As you know, almost all websites now have a degree of interactivity. Whether that be leaving comments, submitting posts, voting or liking other people's submissions, sending an email via a contact form or any of a thousand other possible interactions.

These interactions are impossible using just HTML and CSS. We need to other languages on top or in combination with HTML and CSS in order to allow users to interact with our pages.

Server side vs client side

If you cast your mind back to the class on learning HTML you'll remember we talked a little bit about servers and clients. A server is the computer from which the client remotely requests a web page.

When we put in place interactions in web pages, there are two types of language we use: server-side scripting and client-side scripting.

Server-side scripting is used for things where data is sent to the server and processed by the server. It could be something like leaving a comment on a web page. A user fills in their comment in the web page, presses 'Submit' and the comment is sent to the server. The server then takes the comment and saves it in the database, to show it to everyone else who sees that page.

Most server-side interactions involve the server processing the data and the web page must be refreshed to get the new information.

Client-side scripting is used for (traditionally) smaller tasks, which provide immediate interaction with the user, and generally don't involve sending information to a server. Something like checking that your email address is correct in the comment-form before the form is submitted. Or maybe opening / closing different sections or pop-ups on a web page.

Unfortunately it's not quite this easy as nowadays many web apps use client-side scripting to send data to a server (without navigating to a new page) and then the server can respond with data and the client-side script can update the page with this new data without a page reload.

For the purposes of this class these exceptions aren't really important but you should still know that they exist.

Some examples of server-side languages

Server side languages, then, are run on the server where they process inputs and send the result to the user via (usually) a web page.

The most common server-side language when we're talking about the web is PHP, but there are some others such as:

  • Perl
  • Python
  • ASP
  • Ruby

Some examples of client-side languages

There is only really one major client-side scripting language used on the web nowadays: JavaScript. JavaScript is part of the W3C standards just like HTML and CSS, and just like HTML and CSS the server sends us the 'raw' JavaScript and then it is interpreted and executed by our browser as the web page loads.

JavaScript or JS for short, is a client-side scripting language and has nothing to do with Java, the server-side language.

So basically for most small / medium-sized websites, PHP = back-end, and JavaScript = front-end

...except that one of the biggest up-and-coming server-side languages is NodeJS. NodeJS is JavaScript, but instead of being sent to the browser and read by the browser, it is interpreted and executed by the server like PHP...

...yes it's confusing even for us specialists...

CommitStrip Javascript back-end strip

Meet JavaScript

JavaScript is, then, a client-side language. It's a real programming language (unlike HTML and CSS) because it contains real logic. With JavaScript we can write little scripts (or mini-programs) which do things like:

"If you click on this button here, change the color of my text to blue".

or

"If I click on this button, check if I have entered text in my form. If I have entered text, submit the form, but if the form is empty, pop up a little error message reminding me to fill out all the fields."

Getting started with a programming language

This is a quick introduction to how a programming language works. If you've already written a bit of script or computer programming, you might already know this part!

This is going to be a quick overview of some of the key concepts in a programming language. Hold on, it's gonna be a quick tour...

Variables

Think back to when you learned algebra in School (yes, I know, don't be afraid it's OK really...).

Let's take a really simple example of a mathematical equation:

a + b = c

In Algebra we use letters to represent numbers, and we do an operation on them. In this case, we add a to b.

A variable in any programming language is like a letter in algebra - it stands for another value.

Take a look at the Javascript below:

var a = 12,
  b = 9; // In this line I set the values of a and b

var c = a + b; // In this line I set the value of `c` to that of `a` added to `b`

console.log(c); // This just output's the value of `c` to the console

What would be the value of c in this example? What would be logged to the console?

Variables are simply ways of holding and recalling information in the script.

We can use any keyword (except for a few reserved keywords in Javascript) to name the variable:

var foo = 12,
  bar = 9;

var result = foo + bar;

console.log(result);

Usually we try to use something explicit and clear for the names of our variables, so that reading the code is easy.

Functions

Functions are a little more complex. Functions are like lists of instructions. in most languages functions are written like my_awesome_function(). The brackets at the end indicate 'this is a function'.

We can write functions by using the 'function' keyword and then call them as many times as we like.

// First we define the function
function openAnnoyingAlert() {
  // everything we want to do has to be put inside the {} in the function

  console.log("I will now open an annoying alert");
  alert("This alert is very annoying");
}

// Now we call our function
openAnnoyingAlert();

Functions are very useful when we want to do the same action or process lots of times in different places.

We can also pass 'parameters' to the function. Parameters are values we put inside the () of the function (in a comma-seperated list if there are many) and they allow us to pass a variable to inside the function, and do something to it.

Take a look at the example below:

// First we define the function
function openAnnoyingAlert(alertText) {
  // everything we want to do has to be put inside the {} in the function

  console.log("I will now open an annoying alert");
  alert(alertText);
}

// Now we call our function with our text as a parameter
openAnnoyingAlert("This alert is really annoying");

// We can call it a second time with different text
openAnnoyingAlert("This one is two");

What will this code do?

Try it out for yourself in a browser. Add the following code to any standard HTML file and open it in your browser.

<script>
  // First we define the function
  function openAnnoyingAlert(alertText) {
    // everything we want to do has to be put inside the {} in the function

    console.log("I will now open an annoying alert");
    alert(alertText);
  }

  // Now we call our function with our text as a parameter
  openAnnoyingAlert("This alert is really annoying");

  // We can call it a second time with different text
  openAnnoyingAlert("This one is two");
</script>

return in functions

In most programming languages, we can return things from inside a function.

Let’s say you wanted to get the phrase, “Hello {name}”, where {name} is a person’s name. You can pass their name into a function, and use return to return their name.

function sayHello(name) {
  return "Hello " + name;
}

You can return any valid JavaScript object: strings, booleans, objects, arrays, and even other functions – see below for more types of variable.

The return operator ends a function

Once a return operator is executed, anything after it inside a function doesn’t run.

I often use the return operator to bail or exit the function if certain conditions aren’t met. For example, if a function required an element to exist, you could use return to stop it from running if the element isn’t in the page.

function makeItOrange(element) {
  if (!element) {
    // This 'If' checks if the function exists – more on that later.
    return; // If the element doesn't exist, just exit the function and don't do anything further.
  }
  element.style.color = "orange";
}

Types of variable

In most programming languages, variables have specific types. In the first example the variable was of type 'Integer' - a whole number.

Notice in the second example how the text we put inside the parameters was encapsulated with " ". This indicates that this variable is a string, that is a string of text.

Some other types of variable are:

  • float: a non-whole number like 1.45 or 3.1415651
  • boolean: a yes / no value which is always expressed as either true or false.
  • array: a list of other variables. This is written in Javascript as [ 'value1' , 'value2']
  • object: an object is a complicated kind of varibale to understand. We won't go into it in this class, but you can have a look at it in your own time if you want.

Control structures

If programming was like speaking, then variables are our 'nouns', and functions are our 'verbs'. That means control structures are our 'conditionals'. They allow us to apply computer logic to our scripts and programs.

Take a look at the following function:

function testIfGreaterThan10(number) {
  if (number > 10) {
    console.log("This number is bigger than 10");
    return true;
  } else {
    console.log("This number is smaller or equal to 10");
    return false;
  }
}

testIfGreaterThan10(5);
  • What will this function print to the console?
  • What will this function return?

if...else...

If / Else statements allow us to check a condition (in this case number > 10) and then perform an action if it is true, and something else if it is false.

The syntax in Javascript is a very common syntax (as above).

Inside if...else... structures, we can use any javascript expression that returns a boolean or a truthy value – this could be a simple mathematical expression like number > 10, or it could be a variable, or it could be a function that returns a boolean, an example might be checkIfMyElementExists().

We can also 'chain' multiple else-ifs like so, to add many conditions:

function testColor(color) {
  if (color === "red") {
    console.log("The color is Red!");
  } else if (color === "blue") {
    console.log("The color is Blue!");
  } else if (color === "orange") {
    console.log("The color is Orange!");
  } else {
    console.log("I don't know this color!");
  }
}

for

For loops are slightly more complicated. They allow us to repeat an action a certain number of times.

for (var i = 0; i < 5; i++) {
  console.log("I'm printing to console");
}

This loop will print to the console 5 times.

A for loop has 3 parts inside its bracket:

  • var i = 0: we set our counter variable (by convention called i) to 0.
  • i < 5: this is our loop condition. The loop will repeat as long as this condition is true, so for as long as i is less than 5.
  • i++: we give our loop an instruction to perform at the end of each 'loop'. The instruction here means 'increment i by 1'.

So the loop will run the actions given inside it until i is greater or equal to 5, and after each iteration it will increase i by 1. This means that it will run 5 times.

I made a video explaining this 'Getting to know programming lanugages' a little bit better, and to go over some of the more difficult concepts again!

Exercises

Ungraded Exercise: Is this number bigger than 100

Write a function named isBiggerThan100 that:

  • takes 1 argument, a number.
  • returns true if that number is bigger than 100, false if it doesn't.

Call that function 2 times with different number pairs, and log the output to make sure it works (e.g. "99 is greater than 100: false").

Ungraded Exercise: Which number is bigger?

Write a function named greaterNum that:

  • takes 2 arguments, both numbers.
  • returns whichever number is the greater (higher) number.

Call that function 2 times with different number pairs, and log the output to make sure it works (e.g. "The greater number of 5 and 10 is 10.").

Ungraded Exercise: The world translator

Write a function named helloWorld that:

  • takes 1 argument, a language code (e.g. "es", "de", "en")
  • returns "Hello, World" for the given language, for at least 3 languages. It should default to returning English.

Call that function for each of the supported languages and log the result to make sure it works.

Ungraded Exercise: The Pluralizer

Write a function named pluralize that:

  • takes 2 arguments, a noun and a number.
  • returns a string of the noun and the pluralized form correctly in English, like "5 cats" but "1 dog" etc.

Call the function for a few different nouns and check it works.

Bonus: Add a few irregular plurals like 'sheep', 'geese' and 'children'.

PLEASE NOTE Make sure you attempt the exercises before looking at this page!

Once you've had a go at all of these, take a look at the solutions and see if you were right !