Slides by Liz Krane / @LearningNerd
LearnTeachCode.org/javascript-intro
Follow along on your laptop or phone!
A quirky but powerful and ubiquitous programming language -- it's built into every modern web browser!
Originally a client-side language for making websites more interactive, but now so much more!
Popularity of Programming Languages as of January 2017. Stats by RedMonk, based on data from GitHub and StackOverflow
var colorBox = document.getElementById('colorbox');
colorBox.addEventListener('click', randomColor);
function randomColor() {
// Your code here! Go Googling!
// HINT 1: Find out how to generate a random hex color
// HINT 2: Find out how to use JavaScript to change
// the background color of an element
// HINT 3: Don't forget hex colors need a # in front!
}
// Did you learn anything interesting? :)
// HERE'S THE SOLUTION:
var colorBoxSolved = document.getElementById('colorboxsolved');
colorBoxSolved.addEventListener('click', randomColor);
function randomColor() {
colorBoxSolved.style.background = '#' +
Math.floor(Math.random()*16777215).toString(16);
}
// SOURCE:
// https://css-tricks.com/snippets/javascript/random-hex-color/
Get user input from the HTML <input>
elements
Combine user input with our Mad Lib story
Show finished Mad Lib when user clicks the button
...but how do we do all that??
A variable is a symbolic name for a piece of information that can change over time.
var myName = 'Sally Awesomepants';
Try it out! Copy and paste this code into your console. To run your code, hit enter.
var
keyword to define a new variableVariables can be created with an initial value or without any value at all (undefined
):
var favoriteAnimal = 'penguin';
var favoriteColor;
Try it out! Run this code, then type each variable name (don't forget to press "enter"!) and the console will show their values.
After a variable has been created, you can change it without using the var
keyword:
var favoriteFood = 'salad';
// Actually, I changed my mind!
favoriteFood = 'pizza';
Try it yourself in the console!
Comments are ignored by the computer but very useful for us humans to keep our code organized:
// This is a single-line comment.
/* This is a multi-line comment!
Comments help us humans stay sane. You can use them for:
- notes to explain how your code works
- to-do lists and reminders
- links to sources or references, like this one about JS comments:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Comments
*/
Single-line comments start with //
Multi-line comments start with /*
and end with */
Variables can contain different types of data, like strings, numbers, and more!
var adjective = 'purple';
var favoriteNumber = 3;
The computer stores everything as 1s and 0s, but it interprets the 1s and 0s differently depending on what data type they are.
For example: "0001" might represent the number 1, the letter A, the value TRUE, or something else!
Strings are a bunch of symbols strung together into a sentence, just like alphabet beads on a necklace.
Strings are always surrounded by quote marks, either single (' '
) or double (" "
).
It doesn't matter which you choose, as long as the opening and closing quote marks match!
Photo by Wendy (smkybear) on Flickr
Since strings are always surrounded by quote marks, if your string also contains a quote mark,
you'll run into trouble!
var brokenString = 'I think I'm doing this wrong!';
Try it out in the console. Did you get an error?
Let's see how to fix it...
You can use double (" "
) quote marks to surround a string containing a single quote:
var fixedString1 = "I think I'm doing this right!";
Or vice versa, you can use single quotes (' '
) to surround a string containing a double quote:
var fixedString2 = 'I shouted "Yay!" when it worked.';
You can escape special characters like quote marks by adding a backslash (\
) in front of them:
var fixedString3 = 'Yay, I\'m escaping strings!';
Escape notation is also used for printing special characters like tab (\t
) and new line (\n
).
See more on strings in this reference page.
So you've already defined some strings like favoriteAnimal
and favoriteFood
, but how can you combine them into a sentence?
var sentence = 'My name is ' + myName + ' and I rock!';
Try it! Run this code in your console. Then type "sentence" and hit enter, and you'll see the output:
I am Sally Awesomepants and I rock!
Note: The console remembers the myName
variable that you defined earlier, because it's saved in memory until you close your browser tab. Neat, huh?
Now run this code in your console:
var madLib = 'Yesterday I found a ' + adjective + ' ' + favoriteAnimal + ' with ' + favoriteNumber + ' eyes eating ' + favoriteFood + ' on my dining table and writing JavaScript on my computer! It wrote some code that concatenated strings, so I ran the code and the ouput was: ' + sentence;
After running the code, remember to type madLib
and hit enter to see the value of the madLib string!
The fancy technical term for combining strings is called concatenation. Say that ten times fast!
When used with strings, the + symbol is called the concatenation operator.
console.log(madLib);
at the end!madlibs
somewhere easy to find (maybe on your Desktop)index.html
and save it in your madlibs folderstyle.css
and save it in your madlibs foldermadlibs.js
and save it in your madlibs folder
<!DOCTYPE html>
<html>
	<head>
		<title>Mad Libs! (Girl Develop It LA - Intro to JavaScript)</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width">
		<link href="style.css" rel="stylesheet" type="text/css">
		<link href="https://fonts.googleapis.com/css?family=Waiting+for+the+Sunrise" rel="stylesheet">
	</head>
	<body>
		<h1>Mad Libs!</h1>
		<div id="madlib"></div>
		<strong>Noun</strong> (ex: tree, person): <input type="text" id="noun" class="fill">
		<strong>Past Tense Verb</strong> (ex: jumped, ate): <input type="text" id="verb" class="fill">
		<strong>Adjective</strong> (ex: happy, purple): <input type="text" id="adjective" class="fill">
		<button id="submit">Create Mad Lib</button>
		<p class="small">Based on a practice project from <a href="https://dash.generalassemb.ly/">Dash by General Assembly</a></p>
		<script src="madlibs.js"></script>
	</body>
</html>
body {
font-family: 'Helvetica', 'Arial', sans-serif;
margin: 0 auto;
text-align: center;
padding: 0 20px;
max-width: 800px;
font-size: 25px;
background: #efefef;
}
button {
font-size: 25px;
font-weight: bold;
padding: 10px;
margin: 10px;
}
input.fill {
display: block;
width: 400px;
max-width:95%;
margin:0 auto;
margin-bottom: 20px;
box-sizing: border-box;
}
.fill {
font-size: 30px;
font-weight: bold;
font-family: 'Waiting for the Sunrise', cursive;
letter-spacing: 5px;
background: white;
color: red;
margin-left: 4px;
margin-right: 4px;
padding: 5px 15px;
}
#madlib {
font-size: 30px;
line-height: 2.5;
margin-top: 20px;
margin-bottom: 40px;
}
h1 {
font-size: 80px;
margin: 0;
color: red;
font-family: 'Waiting for the Sunrise', cursive;
font-weight: bold;
letter-spacing: 7px;
}
.small {
font-size:0.5em;
font-style: italic;
margin-top: 30px;
}
In our HTML file, we use the <script>
tag with the src
attribute at the end of the body
element to link it with our JavaScript file:
<html>
<!DOCTYPE html>
	<head>
	</head>
	<body>
		<script src="madlibs.js"></script>
	</body>
</html>
Note that here we assume madlibs.js
is in the same folder as the HTML file that's linking to it.
console.log
!Paste this code into your madlibs.js
file, save it, and then open index.html
in your web browser:
console.log('Hello world!');
Now open the browser console. You should see the message "Hello world!"
The console.log
function displays information in the console. Use it to confirm that your code is doing what you think it's doing!
This log of information is similar to the logbooks used by ship captains to track important events.
Fun fact: most web browsers support fancy customizations, like styling the messages with CSS!
See more advanced tricks in Chrome's documentation
A function is a reusable chunk of code that performs a particular action.
In mathematics, a function transforms input(s) into output. But for JavaScript functions, the inputs and output are optional.
To run or call a function, type its name followed by
( );
with any inputs listed inside the parentheses:
// One string input:
console.log('I am a string');
// Three string inputs:
console.log('string1', 'string2', 'string3');
// Or no inputs at all:
console.log();
Functions in JavaScript can take zero, one, or more inputs separated by commas.
Any variable or data type can be used as input for a function, and you can mix and match:
var favoriteNumber = 5;
// Using a variable containing a number as input:
console.log(favoriteNumber);
var animal = 'penguins';
// You can mix and match data types:
console.log('I found ', favoriteNumber, animal);
JavaScript functions can even take other functions as their inputs! But more on that later.
JavaScript has lots of built-in functions, but you can also create your own!
// Defining a function called shout:
function shout (phrase) {
console.log(phrase + '!!!');
}
// Running (or calling) the function:
shout('I love JavaScript');
shout('Functions rock');
Try it out! First you define your function, and then you can call it as many times as you want.
function shout (phrase) { console.log(phrase + '!!!'); }
function
keywordDefining a function with multiple parameters:
// Defining a function with 3 parameters:
function displayThreeWords (word1, word2, word3) {
console.log(word1 + ' ' + word2 + ' ' + word3);
}
Running the function with multiple arguments:
// Running the function with 3 arguments:
displayThreeWords('pineapple', 'motorboat', 'toothbrush');
Here's a handy way to remember it:
// 3 parameters, don't know the values yet:
function displayThreeWords (word1, word2, word3) {
console.log(word1 + ' ' + word2 + ' ' + word3);
}
// 3 arguments, specific values:
displayThreeWords('pineapple', 'motorboat', 'toothbrush');
To get an output from your function, use the return
keyword followed by the output value:
// Define a function with 1 parameter and an output:
function shout (phrase) {
return phrase + '!!!';
}
// Run the function and save the output to a variable
var myResult = shout('I got some output');
// Display the output
console.log(myResult);
Try it out! Notice that now we can save the results of our function, not just display them in the console.
Keep in mind that console.log
displays information but doesn't save it.
So if you want to use the output from your function later on, you need to return
it!
sayHello
that takes no input parameters and returns as output a string that says hello to the world.makeHeading
that takes one parameter, surrounds it inside "<h1>"
and "</h1>"
, and returns the combination as its output.sayHello
function and save its output in a new variable called greeting
.makeHeading
function, passing it your greeting
variable as an argument, and save its output in greeting
(overriding its old value).Now let's review our project goals again
Get user input from the HTML <input>
elements
Combine user input with our Mad Lib story
Show finished Mad Lib when user clicks the button
...we're almost there!
The DOM organizes HTML pages as a hierarchy of elements, just like the file system on our computers.
It's built into every web browser to let developers
(like us!) modify the contents of our web pages.
The root of the hierarchy/tree is the document
object, which contains all the other objects that
represent our HTML elements.
// Try opening your Mad Libs index.html in your browser,
// and run this in the console to see what's inside:
console.dir(document);
Each of these objects contains properties like the text content of the HTML elements, their HTML attributes, and their CSS styles.
OK, the Document Object Model sounds cool!
So far we've worked with simple variables, but what if we have a whole bunch of them?
var myName = "Sally Awesomepants";
var myProfession = "full-stack JavaScript developer";
var myAge = 32;
var myFavColor = "purple";
var myFavFood = "pizza";
var myFavAnimal = "penguin";
var myFavNumber = 3;
If you have to track this data for hundreds of people, how would you even remember the names of all these variables?! There must be a better way!
You can think of an object as a bag full of variables, just a convenient way to carry them all together:
var me = {
name: "Sally Awesomepants",
profession: "full-stack JavaScript developer",
age: 32,
favColor: "purple",
favFood: "pizza",
favAnimal: "penguin",
favNumber: 3
};
console.log("Hi, I'm " + me.name + ", a "
+ me.age + "-year-old " + me.profession + "!");
This is just one of the ways to create an object, called object literal notation. But more on that later.
Not only can objects contain variables, but they can even contain their own functions!
var myObject = {
myProperty: "Here is some data!",
myMethod: function () {
console.log('Function inside an object!');
}
}
// Access a property of our object:
console.log(myObject.myProperty);
// Run a method of our object:
myObject.myMethod();
Tech jargon tip:
when inside an object, its variables are called properties, and its functions are called methods.
Go to Google.com and then open your browser console once you're on their homepage.
Next, run this code in the console:
document.body.textContent = 'You got hacked!';
OK, just kidding!
Thankfully, it's not that easy to hack a website. These changes are temporary, and they only appear on your computer; nobody else will see them.
Every element in the DOM has a textContent
property that contains the text inside the HTML element it represents. Let's try this out:
// Put this code in your madlibs.js file, then save it
// and open your index.html file in your web browser.
var bodyText = document.body.textContent;
console.log(bodyText);
// SHORTCUT: you could also combine those two lines of code,
// no variable needed:
// console.log( document.body.textContent );
Interesting, right? That's all the text in your web page, without the HTML tags! This can be useful...
First we need a way to identify it! One way is with document.getElementById()
, a built-in method of the document
object for finding one particular element:
var myElement = document.getElementById('test');
It takes one string
as an argument, which should match the ID of the HTML element you want to get.
document.getElementById
!Change me!
The HTML for the box on this page is:
<p id="changebox">Change me!</p>
Let's change its text! Open your browser console while you're on this slide and try running this code:
// Identify the box by its ID:
var box = document.getElementById('changebox');
// Display its current text content:
console.log(box.textContent);
// Change its text content:
box.textContent = 'Voila! JavaScript magic!';
The HTML for this input box:
<input id="changeinput" value="Change me!">
Close and reopen your browser console, then try:
// Identify the input box by its ID:
var input = document.getElementById('changeinput');
// Notice that its text content is empty!
console.log(input.textContent);
// We need to use the value property instead:
console.log(input.value);
// Change its value:
input.value = 'new value!';
So just remember: you need to use the value
property to get the text inside any form elements.
For pretty much all other types of HTML elements, the textContent
property will work fine.
1) Look inside your index.html
file and find the IDs of each input box; you're gonna need them!
2) Create a JavaScript variable containing the value of each input box in your madlibs.js
file by using the getElementById
method of the document
object.
Be sure to look through the previous slides to review what we've learned so far. And don't be afraid to experiment and break stuff; that's the best way to learn!
// Get the values of HTML input boxes
// with the IDs "noun", "verb", and "adjective"
var noun = document.getElementById('noun').value;
var verb = document.getElementById('verb').value;
var adjective = document.getElementById('adjective').value;
// For testing purposes, display the values in the console
console.log(noun, verb, adjective);
Save your madlibs.js
file, open index.html
in the browser, write some text in the input boxes, and then open the console!
Oh yeah, our code runs as soon as we go to our web page (index.html
), before we can type anything into the input boxes! Order of events matters!
When the user clicks the button.
Let's make it happen!
First, let's look at the bigger picture:
The event loop is some code that is constantly running in the background. It checks if any events have happened and runs your code at the right time.
Anywhere you deal with user input, you'll see
event-based programming.
It's built into every web browser too!
See the MDN event reference page for a gigantic list!
You can create chain reactions in your code, not unlike a row of dominoes!
Event-based programming can be harder to learn and harder to debug, so be prepared for some frustration.
Let's look at some code!
document.addEventListener('click', myFunction); function myFunction(event) { console.log(event); }
There are five parts to a standard JavaScript
event listener
Part 1: Where the events will happen
(in this case, the whole HTML document object)
Part 2: Start listening for events
(with JavaScript's built-in addEventListener method)
Part 3: The type of event
(see this reference list or make up your own)
Part 4: The name of the function to run
when the event happens
(known as the "callback" function)
Part 5: This parameter receives an object with info about the event
(different events give you different information)
Let's try it! Open your console and run this code, then click on the page and check the console again.
You should see a MouseEvent object in the console. Click to expand the data:
Each event has different properties, which you can use to control all sorts of cool things!
But more on that later.
Get user input from the HTML <input>
elements
Combine user input with our Mad Lib story
Show finished Mad Lib when user clicks the button
...last piece of the puzzle!
Your code in madlibs.js
should look like this so far:
// Get the values of HTML input boxes
// with the IDs "noun", "verb", and "adjective"
var noun = document.getElementById('noun').value;
var verb = document.getElementById('verb').value;
var adjective = document.getElementById('adjective').value;
// For testing purposes, display the values in the console
console.log(noun, verb, adjective);
madlibs.js
, take all the code (shown on the last slide) and put it all inside a new function called showMadLib
that takes no parameters.createMadLib
, which takes 3 parameters (noun, verb, and adjective), combines them into a sentence, and returns the combined string as output.showMadLib
function, create a variable called madLib
and set its value equal to the result of calling createMadLib
with noun
, verb
, and adjective
as its arguments.
function showMadLib() {
// Get the values of HTML input boxes with the IDs "noun", "verb", and "adjective"
var noun = document.getElementById('noun').value;
var verb = document.getElementById('verb').value;
var adjective = document.getElementById('adjective').value;
// For testing purposes, display the values in the console
console.log(noun, verb, adjective);
// Make the Mad Lib and save it to a variable
var madLib = createMadLib(noun, verb, adjective);
}
function createMadLib(noun, verb, adjective) {
return 'Bob robbed the bank with a deadly ' + noun + ', but then his ' + adjective + ' girlfriend ' + verb + ' the cash!';
}
showMadLib
function (at the end of it), use document.getElementById
to create a JavaScript object for the HTML element <div id="madlib"></div>
textContent
equal to your finished Mad Lib string.
function showMadLib() {
// Get the values of HTML input boxes with the IDs "noun", "verb", and "adjective"
var noun = document.getElementById('noun').value;
var verb = document.getElementById('verb').value;
var adjective = document.getElementById('adjective').value;
// For testing purposes, display the values in the console
console.log(noun, verb, adjective);
// Make the Mad Lib and save it to a variable
var madLib = createMadLib(noun, verb, adjective);
// Make a JavaScript object for the HTML element with id "madlib"
var madLibContainer = document.getElementById('madlib');
// and change its contents to contain our madLib string
madLibContainer.textContent = madLib;
}
function createMadLib(noun, verb, adjective) {
return 'Bob robbed the bank with a deadly ' + noun + ', but then his ' + adjective + ' girlfriend ' + verb + ' the cash!';
}
index.html
file and identify the ID of the submit button.madlibs.js
(not inside any functions), use document.getElementById
again to create a JavaScript object for the submit button.document
with your button object.showMadLib
.
// *** PART 3 CODE (this can be at the top of the file or at the bottom, doesn't matter):
// Make a JavaScript object for the HTML submit button
var submitButton = document.getElementById('submit');
// When submit button is clicked, run the showMadLib function
submitButton.addEventListener('click', showMadLib);
// *** THE REST IS THE SAME AS SOLUTION 2:
function showMadLib() {
// Get the values of HTML input boxes with the IDs "noun", "verb", and "adjective"
var noun = document.getElementById('noun').value;
var verb = document.getElementById('verb').value;
var adjective = document.getElementById('adjective').value;
// For testing purposes, display the values in the console
console.log(noun, verb, adjective);
// Make the Mad Lib and save it to a variable
var madLib = createMadLib(noun, verb, adjective);
// Make a JavaScript object for the HTML element with id "madlib"
var madLibContainer = document.getElementById('madlib');
// and change its contents to contain our madLib string
madLibContainer.textContent = madLib;
}
function createMadLib(noun, verb, adjective) {
return 'Bob robbed the bank with a deadly ' + noun + ', but then his ' + adjective + ' girlfriend ' + verb + ' the cash!';
}
Let's add one final touch to make the Mad Lib prettier...
The textContent
property lets us change the plain text inside an HTML element, but the innerHTML
property lets us use HTML as well as text!
// Copy this code, go to Google.com again,
// open your console and run this code:
document.body.innerHTML = '<h1>Hello world!</h1> <img src="http://i2.kym-cdn.com/photos/images/original/000/114/779/0002.gif">';
Fun, isn't it?? Just don't abuse your new super powers!
In your madlibs.js
file, replace madLibContainer.textContent
with madLibContainer.innerHTML
.
Then surround the noun, verb, and adjective in your Mad Lib string with <span class="fill"></span>
HTML tags like this:
function createMadLib(noun, verb, adjective) {
return 'Bob robbed the bank with a deadly
' + noun + ',
but then his ' + adjective
+ ' girlfriend '
+ verb + ' the cash!';
}
Save it, open index.html
in your browser again, and try it out! Now it's using the custom CSS in your style.css
file!