Code First Girls Logo

A short taster session into the fundamental technologies powering the world wide web.

{{completedPercentage()}}% Complete

Tough Love with JavaScript

This is another group session, so you will need to get back into groups of two or three. This session is a little harder than the last!

This task takes its inspiration from the amazing Jennifer Dewalt - the lady that taught herself to code by building 180 websites in 180 days. Pretty impressive.

We're going to borrow one of her projects and build Tough Love. Have a play.

Find Tough Love here

The idea of this project is to enable you to think like a programmer - being able to break problems down is the most important part of learning to code. Once you can successfully break a problem down into managable chunks you can start to solve it!

Problem Solving

The art of breaking down a problem is so crucial that we will do it in our groups now. Try and do it without looking below!

What will we need to be able to build to create this?

The problems:

The problems that you may have come up with should include:

  • Creating a HTML page with a form input and button
  • Styling that HTML page
  • Being able to read the input in from a user and display it elsewhere when the button is clicked
  • Generating a Tough Love insult
  • Converting the pronouns in the message to second person

Building the HTML

By now you should be comfortable enough with HTML that you should be able to put together a simple site with headers and buttons, but we haven't seen the input tag yet.

<input type="text">

The above extract of HTML creates an input form that accepts text. With this new knowledge you should be able to create a simple HTML page with all the elements that we need.

The headings are for the input message to be displayed and the advice message Remember to get the script tag from here and place it in the <head> Inside the function use an alert('Hello World') so you know it's working Remember $("button").click()?

JavaScript Variables

We'll need to know a little bit more about JavaScript and programming in general before we can crack on with the rest of Tough Love. In particular, we'll need to know what variables and arrays are.

Much like algebra, variables are containers for storing information.

var x = 10;
var y = 20;
var x = x + y;
var sum = 10020;
var company = "Code First: Girls";

var is a keyword in JavaScript that means I want to declarea variable.

Once you've assigned something to a variable, typing the variable name will print out the contents of the variable With the above variables declared, what does x * y equal? Try assigning your name to a variable, you'll need to wrap it in quoteation marks though! This is called a string.

JavaScript Arrays

JavaScript arrays are similar to variables, but they allow you to store multiple values in a single variable. You can consider arrays to be lists, in fact in some programming languages they are called exactly that.

Each of these values is an element of our array and is associated with a number, called an index.

These lists can be particularily useful when we need to represent a list of data that we may need to pick a random element from, or do some operation on each element.

To create an array we use square brackets, and comma seperated lists. For example:

    var myArray = ['First element', 'Second element', Third element];

This creates an array called myArray with three string elements in.

Before arrays can be of much use to us, we need to know how to get elements back out of them. Every element in the array has an index associated with it. The first element in the array is associated with the 0 index, the second element in the array the 1 index etc.

This is a bit weird, but nearly all numbering in computer science starts with zero!

var myArray = ['First element', 'Second element', 'Third element', 'Fourth element', 'Fifth element'];
myArray[0];
myArray[1];
myArray[3];

The above code shows us how to get our elements out of arrays. We use the syntax arrayName[index];

Have at least 4 elements in the array. Use the syntax above to help out Remember, the first element has index 0!

We can do more than just insert and get things out of arrays! There are a couple of really useful methods that you can use with arrays that we will explore now.

var names = ["Nick", "Mark", "Maddie", "Alice", "Alan"];
var lengthOfNames = names.length;

arrayName.length will tell you how many element are in your array. This can be really handy when you need to loop over everything in your array (which we'll do soon!).

var names = ["Nick", "Mark", "Maddie", "Alice", "Alan"];
names.indexOf("Nick");
names.indexOf("Alice");
names.indexOf("Patrick");

arrayName.indexOf("Something") will tell us which index "Something" is at in our array, if it exists at all. If the element we are searching for doesn't exist we will be given back -1.

Try storing that in a new array too. Hint: check the syntax above if you get lost var names = ["Nick", "Nick", "Tom"]; What happens?

Selecting a Random element from an array

var names = ['Nick', 'Alan', 'Trevor', 'Lucy'];
var randomIndex = Math.floor(Math.random() * names.length);
var randomElement = names[randomIndex];

Okay - how does this work?

Math.random() generates a random number between 0 and 1 (but never actually 1, maybe 0.999999).

We then multiply that number by the length of our array. In this case our length is 4, so multiplying a random number between 0 and 1 by 4 will give us a number between 0 and 4 (but again never quite 4, maybe 3.99999).

We then use Math.floor() which takes a number and rounds it down to the nearest integer. So 3.9999 becomes 3. 2.1 becomes 2. We store this as randomIndex

We then use our normal way of accessing array elements to access our random index element!

Verify that it generates a different number between 0 and 1 each time you use it Veryify that multiplying a number between 0 and 1 by another number will generate a number between 0 and that number. with some elements in Verify that Math.random() * yourArrayName.length works too! Verify that this creates a random index that we can use to index our array. You can print our the index by typing index (which is the variable name) Use the code snippet above to get a random element out of your array!

Selecting a random Tough Love

We now have enough knowledge to implement the selection of a random Tough Love message. Guess what? It'll use arrays and variables!

var advice = ["That's terrible! You should knock that off!",
                "Seriously? Why don't you grow the hell up?!",
                "Aren't you a little old for that crap?",
                "You are bad and you should feel bad!",
                "Gross. You are gross.",
                "Are you going to suck all your life?",
                "What? Who does that?!",
                "I thought you were better than that.",
                "My disapproval is overwhelming.",
                " ಠ__ಠ ",
                "Are you freaking kidding me?",
                "NO! Bad!",
                "And when do you plan on becoming an adult?",
                "That is totally unacceptable.",
                "You should be utterly ashamed.",
                "Ugh! That's horrible!",
                "A kitten dies everytime you do that.",
                "I can't believe you are that disgusting."]
You can use Jennifer's if you want. Note: you may find it easier to add an id to the element in your HTML This changes the heading elements text to be our random element

Displaying the input message

We're almost there. We now need to take the message that the user inputs and display it on the page. Once we've displayed it we'll also need to clear the input box.

This can be used to store the input message from the input box. .val() gets the current text that's inside the box. Add this below your code that pulls the random element of the array. Where heading_selector is the CSS selector that selects the heading element from our HTML that we want to display the user input in. This resets the contents of the input box so that it is ready for another input You should now be able to input some text and click the button. The text should be displayed along with a random Tough Love message.

Optional Extras

If you've made it this far and you still have time, try some of these extra exercises

Making it pretty

I'm sure you'll agree the plain HTML site we've created isn't going to win a Webby!

Adding a question mark to the end of the input message

If you study the original Tough Love website you'll notice Jennifer appends a question mark to the end of the message that the user types. We can do this too!

var inputMessage = $('input').val();
inputMessage = inputMessage + "?";

What this does is it gets the value of the text that is currently in the input box, and saves it in a variable called inputMessage.

We then do something called string concatenation to add two strings together. We do this with the + operator, which can be used on strings as well as maths!

inputMessage + "?" adds a question mark character to the end of the input string. We then overwrite the value of out old inputMessage and set the new one equal to this string (with the appended ?)

The code is above and should be placed on the line below $('input').val()

What if the input box is empty?

On Jeniffer's site, if you leave the input box blank and hit submit you get the default "You don't fill in forms?" remark. We should have this on our site.

var inputMessage = $('input').val();
if(inputMessage == '') {
    inputMessage = 'You don't fill in forms';
}
inputMessage = inputMessage + "?";
If you read it out, it sounds like english!

This code uses what's called a conditional statement with an if statement. This checkes the if the condition is true, and if it is executes the code between the curly braces.

In this case, the code checks to see if the inputMessage (the input from the box) is empty == ''. The empty check tests to see if the string in the inputBox is equal to an empty string. If is is, the inputMessage is set to the default You don't fill in forms message.

One important gotcha is the ==. The double equals. This tests for equality. We've seen the = single equals before, this is used to assign something to a variable. Programmers of all experiance get caught out by this at times, don't be one of them.

Can you work out where to put it? Does it work?