From Zero to Website

JavaScript

Your website just got more fun

Believe it or not, we already have most of the tools we need to make a fully-functioning website. However, HTML and CSS impose some frustrating restrictions on web development that get completely blown away when you have some familiarity with JavaScript.

It would be impossible to offer a complete course in JavaScript on one page of an introductory web development course, so let's take a little bit of a different approach to this. Instead of learning JavaScript concepts from the ground up, we'll learn how to do some cool things with an easy-to-use JavaScript library called jQuery.

We'll cover a lot of ground in a short amount of time, and we'll come out on the other side of this lesson with some really, really cool tricks up our sleeves. Onwards and upwards!

JavaScript in the Console

Let's start by opening up the console! To do this, inspect element anywhere on this page, then choose "console" from the tabs at the top of the inspector. Inside the console, type console.log("Hello website!");, and press enter.

The console is like a little JavaScript sandbox. When you write JavaScript statements in the console, it gets interpreted just like any JavaScript that might have already been included on the website. That means the console is a great place to experiment with JavaScript! Bear in mind that anything you do in the console only affects your current session in your browser. So, if you mess anything up super bad, you can always just refresh.

You can open up the console on any website you visit! Because any JavaScript errors also get reported to the console, there might already be a lot of garbage inside the console, depending on the site. No matter what, though, you'll always be able to type things into the console and play around with the HTML on the website.

You can also use console.log statements in JavaScript files. It'll print whatever you put inside the parentheses to the console.

One last thing: you should run all of the JS snippets from this lesson in your console. If you want to live life to the fullest, try modifying each of the snippets a little bit after running them to make sure you understand what's happening and see what works.

JavaScript Variables

In JavaScript, we need to be familiar with the concept of a variable. Variables provide a way for us to store values.

var myFavoriteRapper = "Drake";
console.log("My favorite rapper is " + myFavoriteRapper);

This is a short snippet of JavaScript, but there's a lot to talk about! Let's start by breaking the first line into five separate components.

  1. The keyword var indicates that we're declaring a variable.
  2. The name myFavoriteRapper is how we'll refer to this variable in the code after this line in our JavaScript file.
  3. The = sign is the assignment operator in JavaScript. It stores whatever value is on the right side of the operator into the variable on the left side.
  4. "Drake" is the value being stored into the variable.
  5. The semicolon, ;, indicates that the statement is finished. Every JavaScript statement must end in a semicolon. For now, we can think of a statement as being equivalent to a line of code.

The second line of code in that snippet should look familiar. We're just logging something to the console, but notice what's inside the parentheses: "My favorite rapper is " + myFavoriteRapper. This expression gets evaluated to the string "My favorite rapper is Drake", because you can add strings together with a + sign in JavaScript. myFavoriteRapper contains the string "Drake", so JavaScript puts the two strings together; it doesn't care that one of the strings is stored in a variable.

Now let's look at an extended version of this snippet.

var myFavoriteRapper = "Drake";
console.log("My favorite rapper is " + myFavoriteRapper);
myFavoriteRapper = "Kendrick";
console.log("Just kidding. It's " + myFavoriteRapper + ".");

Now that we've already declared the myFavoriteRapper variable, we don't use the var keyword anymore when we want to change the variable's value. Now, when we use the variable in the last line, JavaScript evaluates it to the value to which it was most recently set: "Kendrick".

If you ran that snippet in the console, or put it in a JavaScript file, you would get the following output:

My favorite rapper is Drake
Just kidding. It's Kendrick.

Grouping values with arrays

Before we take a look at all the tricks we can do with jQuery, we need to cover one more JavaScript fundamental: the array. Arrays are useful for storing groups of values, where it would be unwieldy to have a variable for every single one.

var numbers = [4, 8, 15, 16, 23, 42];
console.log(numbers[1]);

In this example, numbers is a variable that stores an array that contains six values. We can access these values with the syntax arrayName[index]. So, the expression numbers[1] will evaluate to the whatever's stored at position 1 in in numbers.

However, the thing that's stored at position 1 in numbers is actually 8! That's because arrays are zero-indexed in JavaScript, meaning that the indices start at 0. So, to get the first element in numbers, we would need to write numbers[0].

Let's take a break for a second! We're going through these concepts really quickly. I'd recommend going back and rereading the JavaScript we've covered up until now, making sure you understand everything that's going on in the snippets.

If you don't understand everything completely, please read Chapters 1 and 2 of Eloquent JavaScript. It offers a much more complete background to what we're doing now.

If you do understand all the snippets, read Chapters 1 and 2 of Eloquent JS anyway! Read more if you have the time. Trust me when I say that it will serve you well in the long run.

Also, it's OK if this stuff feels hard. JavaScript is such a vast and deep topic that it's impossible to get the hang of it quickly. Remember: if you meet anyone who says they're a JavaScript expert, they are either very very experienced or wrong.

Once you feel like you're up to speed, we'll learn how to make it work with HTML!

Putting JavaScript on your website

Inserting JavaScript into a website is pretty similar to linking to a CSS file. Use a script element to include your file right at the bottom of your body:

<!DOCTYPE html>
<html>
    <head>
        <!-- All your head attributes -->
    </head>
    <body>
        <!-- Content goes here -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script src="/js/index.js"></script>
    </body>
</html>

Note that, based on the src attribute of the script, index.js is inside a folder. This follows the same pattern we established in the CSS lesson: create a folder called js and put it at the same level as your index.html, so that any JavaScript files will live inside that new folder. Your files should now look like this:

website/
  - css/
    - style.css
  - js/
    - index.js
  - index.html

jQuery is your friend

jQuery makes JavaScript easier to use. With jQuery, selecting all the paragraphs on a page is as easy as $('p'), where the pure-JS analog would look like document.getAllElementsByTagName('p'). Anytime you see or use a $ in JavaScript, that means you're using some features from jQuery.

Before we go any further, let's draw some hard lines about what jQuery is and how to use it.

What jQuery Actually Is

In the introduction, I said that jQuery was a JavaScript library, but I didn't explain any further. What that means is that it's a collection of pre-written JavaScript utilities that abstract away a lot of the headaches caused by doing things in JS that feel like they should be easy, but end up being complex and annoying. jQuery isn't another programming language, even though it can feel like one sometimes: that means that you can use jQuery in normal JavaScript files, as long as you import the jQuery library on your website.

Importing jQuery

There are a couple of ways to put jQuery on your website, but the one I'd recommend is by letting Google host it. This is actually the same way Google Fonts works: you just link to the content from Google before you link to your own code. Again, the snippet goes at the bottom of the body:

<body>
    <!-- Content goes here -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="/js/index.js"></script>
</body>

OK! We're ready to do some wild things using jQuery and JavaScript.

Using jQuery selectors

As I mentioned before, selecting all the paragraphs on the page is as easy as $('p') when you use jQuery. Selecting things in jQuery works a lot like CSS: you can select based on class names or tag names, and you can combine selectors with commas.

$('a')
$('.major-key')
$('h1, h2, h3, h4')

Each of these selections returns an array of HTML elements—just like arrays can contain numbers or strings, they can also contain more complex objects like HTML elements. For example, $('a')[0] would give you the first link on the page. Try this in the console now!

This means that jQuery makes it really easy for us to manipulate a lot of HTML elements all at once. For example, we can change the content of HTML elements really easily. Try running the following line of code in your console:

$('.inline-code').html('lol');

(Unfortunately, there is no concept of an “undo” button in the console. Remember how I said you'll sometimes have to refresh to get things back to their original state?)

There are other, less destructive things you can do with HTML in jQuery. Let's take a quick look now:

// Returns content of first HTML element that matches the selector
$('.inline-code').html();

// Inserts HTML snippet at end of element (inside the element)
$('h3').append(' <a href="https://www.youtube.com/watch?v=iZJXvjeWlVA">:O</a>');

// Inserts HTML snippet after element
$('h3').after('<p>Time to learn!</p>');

The opportunities are endless! The world is your oyster!

Handling events with jQuery is a major key

What we've seen so far makes it easy to do some silly things. But what if we could manipulate HTML elements depending on what the user does? Suddenly, we'd have a lot more power. That's what events are for! Let's take a look at an example.

$('.inline-code').on('click', function() {
  $(this).html('wow lol');
});

This is a snippet that changes the content of every .inline-code element when you click on it. Copy and paste it into the console to see what the effect is! Let's go through it carefully to understand what's really going on.

// For everything that matches this selector,   when you click it,   do this thing:
$('.inline-code')·······························.on('click',········ function() {

// Change only the clicked element's HTML content to   "wow lol".
  $(this).html········································ ('wow lol');

}); // (closing parens and braces as necessary)

Along with click events, there are some other events that are useful to know when building things with jQuery:

Manipulating CSS with jQuery

One of the most useful things you can do with jQuery is changing CSS based on certain events. Just like we can manipulate HTML content with html, we can change all kinds of CSS using css.

$('p').on('click', function() {
  $(this).css({
    "color": "#42cbad",
    "font-weight": "700",
    "line-height": "40px",
    // "attribute": "value",
  });
});

Note that each property-value pair is in quotes, and goes inside curly braces ({}). Also, each pair has a comma after it, though the comma on the last pair is optional.

One big disadvantage of this approach is that you can't bring any clicked element back to its original state. What if we wanted to just switch between styles on every click? There are some ways to do that with just JavaScript, but the most elegant solution involves CSS, too!

/* I included this in my CSS so that you could run the snippet below! */
.extra-cool-text {
  color: #42cbad;
  font-weight: 700;
  line-height: 40px;
}
$('p').on('click', function() {
  $(this).toggleClass('extra-cool-text');
});

Now, instead of manipulating CSS attributes directly with JavaScript, we're just changing whether each element has a class applied to it. toggleClass is extremely useful.

Animating things with jQuery

One of the most fun, and equally useless, things you can do with jQuery is animation! jQuery makes this incredibly easy. The code looks a lot like changing CSS, but you must also provide the number of milliseconds you want the animation to take.

$('h3').on('mouseover', function() {
  $(this).animate({
    "letter-spacing": "10px",
    "font-size": "40px"
  }, 1000);
});

Tears of joy. You can also chain animations together to specify an order, like this:

$('h3').on('mouseover', function() {
  $(this).animate({ "font-size" : "40px" }, 400)
  .animate({ "letter-spacing" : "10px" }, 1000);
});

Note that I'm formatting the code a little differently in this snippet: I'm fitting more stuff on one line. That's because JavaScript doesn't care about whitespace or whether or not you have newlines (i.e. press return) between different statements. When you chain animations together, you might find it easier to read visually when you put each animation on its own line.

You can also give the animation something called a callback function: some code that will run after the animation finishes. This is optional, and comes after the animation length, separated by a comma, like this:

// Run this in the console, then click me
$('.language-javascript').on('click', function() {
  $(this).animate({
    "height" : "0px",
    "padding": "0px"
  }, 400, function() {
    alert("goodbye world"); // like console.log() but better
  })
});

You can put anything that's valid JavaScript inside of that callback function.

One last thing about jQuery

Before I send you off into the real world of jQuery silliness, I have one last piece of advice, and it's important.

You can't safely manipulate any HTML until all of the content has actually been loaded. You'll experience some strange and frustrating bugs if you try to do so. But how do we know when the page is safe for JavaScript? It seems like a difficult problem.

$(document).ready(function() {
  ...
  // All JS code goes here!
  ...
});

Well, it is indeed a difficult problem, but it's not one you have to solve! This is another great feature of jQuery. As long as you put all of your code inside those beginning and ending lines, you'll never experience the pain of those problems.

Cool! We've put together a pretty hilarious toolbox of effects with jQuery. Let's review some language from this lesson, then dive into a mini-project.

Terms

JavaScript
A programming language for the web, created in May 1995 in 10 days by Brendan Eich.
JavaScript library
A collection of prewritten utilities in JavaScript.
jQuery
An all-purpose JavaScript library.
console
The browser's interface between you and JavaScript.
keyword
A reserved word in JavaScript (or any other programming language!). Examples of keywords would include var or function.
variable
A container that stores a value. Every variable has a name, assigned by the programmer.
declaring a variable
Creating a variable for the first time. Requires the var keyword.
statement
A complete JavaScript operation, analogous to a sentence.
evaluate
The process by which JavaScript determines an expression's value.
array
A structure that contains 0 or more values.
zero-indexed
Describes the convention that states that the first element in an array has an index of 0.
event
Any of several different user actions performed in the browser, e.g. click, mouseover, mousemove.
callback
A function that gets executed once the current function has finished.

Very Serious Assignment

Getting started

To get started, make sure your directory structure looks like what we covered above, and make sure your HTML file links to both jQuery and to your own JavaScript file.

Your mission

Let's do some fun stuff with jQuery! Like all our assignments have been, this one will be pretty open-ended: all I ask is that you spend at least 45 minutes goofing around with the effects we talked about. If you want some inspiration, here are some ideas!