{ The Rithm Blog. }

A Roadmap for Learning How To Code - Part 3 June 13, 2018

This blog post is next chapter of the "Roadmap for Learning How to Code" series for beginners, check out Part 1 and Part 2 if you haven't yet!

In this chapter we are going to learn the fundamentals of web scripting using JavaScript.

Chrome DevTools - The Console

If you've started to learn programming in a language other than JavaScript, for instance Python, you may have had to download and install software that runs the language.

The great thing with JavaScript is that you already have a very powerful software package that can compile, execute, and even interactively debug JavaScript. It's your web browser!

Here at Rithm, we're going to recommend you specifically use Google Chrome (download), which at the time of this blog post is still the de facto standard/preferred browser for web developers (as well as the dominant browser among users by market share).

Go ahead and open up the Chrome console (yes, on the current page -- this blog post!).

Here are the keyboard shortcuts in case you've forgotten:

Chrome DevTools Keyboard Shortcuts

(I'm writing this on a Mac so I'm going with Command+Option+J).

Hello World

For whatever reason most "learn how to code" tutorials always start with hello world. But why stop at world? In the console let's type:

alert('hello universe');

...and press enter/return.

Congrats! This is (presumably) first web script. This line of JavaScript was compiled and executed in real-time by your browser, and you were able to render an alert box on the screen with a single command.

Keep the console open, because we're going to be doing lots of stuff with it for the rest of this post.

The DOM

The first important term to understand before we get started is the DOM, which stands for the Document Object Model. Basically, every webpage on the internet consists of at least one HTML or XML document. The DOM simply gives you access to the current document through JavaScript objects. We'll talk much more about the specifics of JS objects later, but for now you can just think of an object as a collection of attributes and functions.

We've already interacted with the DOM by calling alert('hello universe'). The real name for alert was window.alert. In other words, that means that the alert function is part of your browser's window, which affects the DOM.

You can read much more about the DOM in this nice MDN article here, and of course in our free curriculum here. Now that we have a basic definition, however, let's start selecting things!

Selecting Web Elements with JavaScript

A brief glimpse at the elements tab of this very page shows that it's got a lot of markup. It's difficult to find things by hand, so the DOM has methods (functions) that we can use to find things much easier.

Getting Elements

The easiest way to select a specific element is by its ID, if it has one. For example, we can select the entire blog post because it has an ID of blog-post. Just type the following code in the console:

document.getElementById('blog-post');

It should print the element, which you can mouseover and select / modify the styles, etc.

document.getElementById is probably the easiest way to find things for beginners, but there are plenty of other similar methods. Go ahead and type document.get and don't press enter. Chrome will show you a big list of methods you can employ:

  1. document.getElementById
  2. document.getElementsByClassName
  3. document.getElementsByName
  4. document.getElementsByTagName

...and more.

You should be able to figure out what they do by name, but let's try another one anyway.

document.getElementsByTagName('div');

This is going to give us all the divs on the page, and wow there are 62 of them. We get all of these elements in a list called an HTMLCollection, which lets us go through it in JavaScript.

Query Selectors

My favorite way to select elements using JavaScript is by using the document.querySelector method. This lets us use CSS selectors which we've already spent the time learning (see the previous blog post for a refresher) to select things:

document.querySelector('.container');

This selects the div holding everything on this page -- the one with the class="container" (since . is the CSS class selector).

But notice if you do something like:

document.querySelector('p');

...you would hope that it selects every paragraph on the page, but it only selects the first one it finds.

To get all of them, we need to use document.querySelectorAll('p'). That way we can select all 50+ paragraph tags at the same time on the page, if we need to.

A Note on Methods

Don't try to memorize these! They're so easy to lookup and there are so many of them. As a rule of thumb, I tell students the most important ones to remember are document.querySelector and document.querySelectorAll. That way, as long as you know some basic CSS selector syntax, you can get pretty much anything you're looking for.

For a more thorough and complete introduction to selecting DOM elements, check out our free curriculum here!

Manipulating Web Elements with JavaScript

Selecting things only gets us so far. So what if we can find things with JavaScript? The fun part is messing with things!

Changing the Blog Post Background Color

Let's start by making the background a different color here. First we'll need to select the div that's giving the post a white background. It's got a class of card.

Let's use querySelector and we'll assign the card div to a variable (essentially giving that div a JavaScript nickname) so we can reference it easily.

var card = document.querySelector('.card');

To change the background color with JavaScript, we need to mess with the style properties like so:

card.style.backgroundColor = 'chartreuse';

Nice!

Changed Background Color

Couple of notes:

  1. Any CSS property can be found on the element.style object.
  2. Changing the element.style is going to mess with inline-styles. It won't touch your CSS stylesheet, and if you refresh the page, everything is back to the way it was.
  3. JavaScript uses lowerCamelCase name case conventions. That means every CSS property is going to start lower-cased, and any subsequent word will have a capital letter after it. For example, we write CSS with kebab-case (aka dash-case) background-color, but in JavaScript it's going to be backgroundColor instead. ¯\_(ツ)_/¯

To get better at manipulating DOM stuff, as always check out our free curriculum here!

Intro to Events

Let's move on from messing with this blog post and start our own files so we can do more interesting stuff.

We'll start with these three files:

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div class="container">
    <div id="color_box"></div>
    <button id="color_changer">Click Me!</button>
  </div>
</body>
<script src="main.js"></script>

</html>

style.css

.container {
  text-align: center;
}

#color_box {
  margin: 100px auto;
  height: 400px;
  width: 400px;
  border: 5px solid black;
  border-radius: 5%;
}

#color_changer {
  background-color: palegreen;
  border: 0;
  padding: 20px;
  border-radius: 5%;
}

#color_changer:hover {
  background-color: darkseagreen;
  cursor: pointer;
}

main.js

var button = document.getElementById('color_changer');
button.addEventListener('click', function() {
  alert('YOU CLICKED THE BUTTON!');
});

Result

Here's what you should get when you copy and paste these, and open index.html and click on the button:

Example Page with Button Clicked

A couple of notes before we talk about the functionality:

  1. These three files index.html, style.css, and main.js are going to be pretty standard "boilerplate" files for a while when you're starting out!
  2. The CSS file is linked in the <head> because we want the styles to load before the rest of the page.
  3. The JavaScript file is linked after the </body> closing tag because we want the JavaScript to load last. This is because JavaScript files can get pretty huge and we generally want to be able to see the markup and styles right away instead of staring at a blank page until the JavaScript is done downloading.
  4. The JavaScript tag <script src="main.js"></script> is pretty self-explanatory, just point src to any .js file in the same folder. You can have multiple script tags if you want to use more than 1 file (more on that later).

The Event Listener

If we take a look at main.js, we can see that on line 1 we are selecting the button and assigning it to a variable. Then on line 2, we are adding a click event listener and a callback function. The behavior of this should make intuitive sense just looking at it, but to be particular, what is going on is that you have a function that runs every time a click event is registered on the button we've selected.

The entire JavaScript file runs as soon as the page loads, with the exception of the code inside this callback function. The code in here only runs whenever you click the button. We can say that the callback gets triggered or invoked upon click, because we specifically said "hey button, listen for 'click' events".

There is much, much more to say about events, callbacks, and JavaScript itself. But for now, let's just appreciate the fact that we made some code run dynamically in response to user input! That's great!

Read much more about events here in our free curriculum.

Summary

In this edition of the article, we are again skimming the surface of a lot of rich and complex topics. But the goal is to get our hands dirty as soon as possible and experience the most exciting parts of beginning web development first, so these quick wins make us intrigued to learn more about JavaScript syntax, HTML/CSS, and the DOM.

Here are some self-review questions to retain stuff from this article:

  • What is the shortcut to open the Chrome DevTools (any of the three will do 😉)?
  • How do you use the document.querySelector and document.querySelectorAll methods (i.e. what do you give them, what do they give you)?
  • If I have an element with an ID of rithm, what are two different methods I can use to select it?
  • Why does the <script> tag usually go after the </body> closing tag?
  • How is our button's callback function different from the rest of the JavaScript code in main.js? (hint: when does it happen)

Look for our next edition of this blog post soon which will take our understanding of JavaScript / web development to the next level.

In the meantime, to continue learning how to code, it's time to start getting into more JavaScript syntax basics here.

Final Exercise

Use what you've learned to make it so that, in the provided code, clicking the button no longer gives an alert to the user, but instead it changes the background color of the div box, like so:

Color Box Changing

USE ONLY JAVASCRIPT TO DO SO!

BONUS: Make the background color any random color.

Here's a JavaScript array containing all of the named CSS colors to get you started:

var colors = [
  'aliceblue',
  'antiquewhite',
  'aqua',
  'aquamarine',
  'azure',
  'beige',
  'bisque',
  'black',
  'blanchedalmond',
  'blue',
  'blueviolet',
  'brown',
  'burlywood',
  'cadetblue',
  'chartreuse',
  'chocolate',
  'coral',
  'cornflowerblue',
  'cornsilk',
  'crimson',
  'cyan',
  'darkblue',
  'darkcyan',
  'darkgoldenrod',
  'darkgray',
  'darkgreen',
  'darkgrey',
  'darkkhaki',
  'darkmagenta',
  'darkolivegreen',
  'darkorange',
  'darkorchid',
  'darkred',
  'darksalmon',
  'darkseagreen',
  'darkslateblue',
  'darkslategrey',
  'darkturquoise',
  'darkviolet',
  'deeppink',
  'deepskyblue',
  'dimgray',
  'dimgrey',
  'dodgerblue',
  'firebrick',
  'floralwhite',
  'forestgreen',
  'fuchsia',
  'gainsboro',
  'ghostwhite',
  'gold',
  'goldenrod',
  'gray',
  'green',
  'greenyellow',
  'grey',
  'honeydew',
  'hotpink',
  'indianred',
  'indigo',
  'ivory',
  'khaki',
  'lavender',
  'lavenderblush',
  'lawngreen',
  'lemonchiffon',
  'lightblue',
  'lightcoral',
  'lightcyan',
  'lightgoldenrodyellow',
  'lightgray',
  'lightgreen',
  'lightgrey',
  'lightpink',
  'lightsalmon',
  'lightseagreen',
  'lightskyblue',
  'lightslategrey',
  'lightsteelblue',
  'lightyellow',
  'lime',
  'limegreen',
  'linen',
  'magenta',
  'maroon',
  'mediumaquamarine',
  'mediumblue',
  'mediumorchid',
  'mediumpurple',
  'mediumseagreen',
  'mediumslateblue',
  'mediumspringgreen',
  'mediumturquoise',
  'mediumvioletred',
  'midnightblue',
  'mintcream',
  'mistyrose',
  'moccasin',
  'navajowhite',
  'navy',
  'oldlace',
  'olive',
  'olivedrab',
  'orange',
  'orangered',
  'orchid',
  'palegoldenrod',
  'palegreen',
  'paleturquoise',
  'palevioletred',
  'papayawhip',
  'peachpuff',
  'peru',
  'pink',
  'plum',
  'powderblue',
  'purple',
  'rebeccapurple',
  'red',
  'rosybrown',
  'royalblue',
  'saddlebrown',
  'salmon',
  'sandybrown',
  'seagreen',
  'seashell',
  'sienna',
  'silver',
  'skyblue',
  'slateblue',
  'slategray',
  'snow',
  'springgreen',
  'steelblue',
  'tan',
  'teal',
  'thistle',
  'tomato',
  'turquoise',
  'violet',
  'wheat',
  'white',
  'whitesmoke',
  'yellow',
  'yellowgreen'
];

Final Exercise Solution

Here's the solved exercise in a codepen: https://codepen.io/hueter/pen/RJgYqY

Written by Michael Michael

Back to all posts