Similar to how we use CSS, javascript can be used embedded or linked
<script type="text/javascript"> console.log('hi class~');</script>
<script src="example.js" type="text/javascript"></script>
Like with CSS, the linked
approach is the best way to use javascript.
Javascript is executed line by line as the html document is parsed
.
The document parsed these lines one by one:
<!-- 1 --><!DOCTYPE html><!-- 2 --><html lang="en" dir="ltr"><!-- 3 --> <head><!-- 4 --> <meta charset="utf-8"><!-- 5 --> <script src="example.js" type="text/javascript"></script>
So if we have anything in our script that refers to html elements in the page, those won't exist yet and result in errors...
So remember we need to add the defer
attribute to our linked script tags to tell the browser to apply Javascript
code after the page has been completely parsed.
<head> <meta charset="utf-8"> <script src="example.js" defer type="text/javascript"></script></head>
note this will only work for externally loaded files. Embded javascript, you'll need to place the script tag after the body or use other techniques we'll learn more about later..
A variable is a container for a value that we can use throughout our code.
We define a variable by using the let
keyword in front of it.
// variables can be any name you want..// so long as they are only made up of letters!let myVariable = 'hi';// this won't worklet my variables = 'hi';// nor will this!!let my-variable = 'hi';// try to avoid thislet my2ndVariable = 'hi';// this is ok, but javascript convention is to use "bumpy" caselet my_variable = 'hi';
There are several ways values can be represented in code, what we refer to as types
.
A string
is just a piece of text wrapped in either ''
single or ""
double quotes. Strings are made
up of characters (like the a
in "apple"). These sequences of characters strung together comprise a string
: )
let myPoem = 'A long string / stung my head / to recall it';// Strings are used often in javascriptdocument.querySelector('#my-blog'); ^ string here
A note on convention: it's usually best to use ''
single quotes in your javascript code, and double quotes ""
for things like your html attributes
A boolean
is a value that is either true or false. They function as a toggle or flag, and
are the value that conditionals check for.
let isItNightOut = true;if (isItNightOut) { document.querySelector('.fireflies').classList.add('wake-up');}
Variables can hold lots of different values.. like strings
and numbers
:
let myNumber = 10;// we can use console.log to see the variable in the consoleconsole.log(myNumber);let anotherVariable = 'hi';console.log(anotherVariable);// we can reuse a variable once we've created it!// note that we don't re-define it with `let` before// since it already existsanotherVariable = 'ho';console.log(anotherVariable);// here we're adding together the string "hi" to// our `anotherVariable` that is equal to "ho"let offToWorkWeGo = 'hi ' + anotherVariable;console.log(offToWorkWeGo);
A conditional
is a way that we can ask a question and do different things based on the answer.
Conditionals are written with an if
statement with the question wrapped in parentheses ()
and
the code to run if the question is true in { ... }
curly brackets:
let name = 'goose';if (name == 'goose') { console.log('run!!!');}
Often we use conditionals to compare one value to another. The way we compare values is with Comparison Operators
.
Above we're using the ==
comparator, which asks is the value on the left is the same as the value on the right.
Recall we can check for additional conditions with
else if
and else
:
let name = 'duck';if (name == 'goose') { console.log('run!!!');} else if(name == 'horse') { console.log('um.. what game are you playing?');} else { console.log('whew!');}
Here we and an else if
condition checking for another possible value and an else
for when the first two conditionals aren't true.
The questions you pose in conditionals can also be combined together to check for more complex conditions, for instance finding a range between two numbers.
The two ways to combine these questions are with operators
:
&&
which stands for and: if (<thing is true> AND <thing is true>)
||
which stands for or: if (<thing is true> OR <thing is true>)
let age = 14;if (age >= 13 && age <= 19) { console.log("You're a teen!");}if (age < 13 || age > 19) { console.log('You are not a teen!');}
Reworking last weeks guessing example:
/* __// /.__.\ \ \/ / '__/ \ \- ) \_____/ -cf_____|_|____ */let eggs = '000000000000000000000000000000000000000000000000';let guess = window.prompt("Guess how many eggs?", 5);console.log("You guessed: " + guess);// how many eggs do we have?if (guess < eggs.length || guess > eggs.length) { console.log("you're wrong!");} else if (guess == eggs.length) { console.log("bingo!");}// or could be written:if (guess == eggs.length) { console.log("bingo!");} else { console.log("you're wrong!");}
Let's recap how we access html elements in our Javascript code with querySelector
.
Remember that querySelector
is a way to search for elements in our document based on selectors — like the
css selectors we've learned about:
let blogPost = document.querySelector('#blog');
Document refers to the DOM
document.
You can even use pseudo-classes
:
let lastGraph = document.querySelector('p:last-child');
example.js:
let blogElement = document.querySelector('#blog');console.log(blogElement);
example.html:
<!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <script src="example.js" defer type="text/javascript"></script> </head> <body> <main id="blog">hello class</main> </body></html>
Now that we have a reference to our element in javascript, we can do something with it like adding a class:
.red { color: red;}
The classList
attribute of a html element in javascript provides tools for adding, removing, and checking
whether an element has a class.
let blogElement = document.querySelector('#blog');blogElement.classList.add('red');
Functions are a powerful concept that most programming languages employ.
They allow us to set aside a group of instructions or code to execute at some later point.
Functions are composed by specifying the function
keyword and then providing a custom name for your function
.
The name is how we will later refer to it.
function myFunction() { // code to run later when we call the function goes in here}
at some later point...
myFunction(); // lets call our function
Functions can optionally receive additional details, called arguments
, to make
them more extensible and useful:
function sayHi() { console.log('Hi Josephine.');}sayHi();sayHi(); // say hi again
Instead of making the message we write to console fixed, we could use an argument
to
make the message we write dynamic:
function sayHello(name) { console.log('oh, hello ' + name);}sayHello('Josephine');sayHello('Maryam'); // say hello to someone new
arguments
within a function
are variables
that only exist within the scope
or context
of the function.
An important aspect of functions is that they help break up our code so that we don't have to repeat ourselves by copying and pasting code.
We could instead incapsulate that code in a function and call it whenever we want to preform that set of actions.
// from our previous examplelet blogElement = document.querySelector('#blog');blogElement.classList.add('red');let blogElement = document.querySelector('footer');footer.classList.add('red');// lets make this more reusablefunction makeRed(element) { element.classList.add('red');}let blogElement = document.querySelector('#blog');makeRed(blogElement);makeRed(document.querySelector('footer'));
Another useful thing functions can do is send back a value from the code it contains.
We use the return
keyword to send back some value to the place where it was called.
function scream(text){ return text.toUpperCase() + '!!!!';}let shouting = scream('hello class');console.log(shouting);console.log(scream('I hope this is all making sense 😅'));
So we can define a list of instructions that we might need to repeat often, call it at whatever point we want, but also return some result from that work to use.
Now that know how to reference an html element in our page, we can listen for events on that element and perform actions based on it.
To listen for events on an element, we use addEventListener
.
The addEventListener
method tells the browser to listen or watch an element for events
that we specify and then call a function to run some code once that event occurs.
We add listeners to the reference for a html element that we retreived from document.querySelector
:
<button class="click-me">Click me!</button>
function clickMe() { console.log('thanks for click~');}let button = document.querySelector('.click-me');button.addEventListener('click', clickMe);// ^ event ^ function to call when event occurs
Note that when we provide the function we want to be called to the listener, we don't include the ()
parentheses.
button.addEventListener('click', clickMe);
When we use clickMe()
with the parentheses on functions, the function is called at that moment.
// wrong ! : ((button.addEventListener('click', clickMe());
But since we want our function to be called later on when the event occurs, we only need to pass the
reference
or name of the function, and not the clickMe()
full invocation of it.
There are all kinds of events we can respond to, for instance mouseover
:
function hoverElement(event) { console.log(event); } let poem = document.querySelector('.borges-poem'); poem.addEventListener('mouseover', hoverElement);
<div class="borges-poem"> <p> I, who have felt the horror of <span>mirrors</span><BR> Not only in front of the <span>impenetrable crystal</span><BR> Where there ends and begins, uninhabitable,<BR> An impossible space of <span>reflections</span>, </p> <p> But of gazing even on water that <span>mimics</span><BR> The other blue in its depth of sky,<BR> That at times <span>gleams back</span> the illusory flight<BR> Of the inverted bird, or that ripples, </p></div>
poem via http://www.cabinetmagazine.org/issues/14/borges.php
I, who have felt the horror of mirrors
Not only in front of the impenetrable crystal
Where there ends and begins, uninhabitable,
An impossible space of reflections,
But of gazing even on water that mimics
The other blue in its depth of sky,
That at times gleams back the illusory flight
Of the inverted bird, or that ripples,
As you can see, our event has a bunch of info, but one thing of interest is the target
or the thing triggering the event.
Let's log the target to the console:
function hoverElement(event) { console.log(event.target.tagName);}let poem = document.querySelector('.borges-poem');poem.addEventListener('mouseover', hoverElement);
I, who have felt the horror of mirrors
Not only in front of the impenetrable crystal
Where there ends and begins, uninhabitable,
An impossible space of reflections,
But of gazing even on water that mimics
The other blue in its depth of sky,
That at times gleams back the illusory flight
Of the inverted bird, or that ripples,
We could add a conditional
that checks whether we're hovering over a span element:
function hoverElement(event) { if (event.target.tagName == 'SPAN') { event.target.classList.add('yellow'); }}let poem = document.querySelector('.borges-poem');poem.addEventListener('mouseover', hoverElement);
Let's also add some transitioning css:
span { transition: background .5s ease-in-out;}
I, who have felt the horror of mirrors
Not only in front of the impenetrable crystal
Where there ends and begins, uninhabitable,
An impossible space of reflections,
But of gazing even on water that mimics
The other blue in its depth of sky,
That at times gleams back the illusory flight
Of the inverted bird, or that ripples,
Keyboard shortcuts
↑, ←, Pg Up, k | Go to previous slide |
↓, →, Pg Dn, Space, j | Go to next slide |
Home | Go to first slide |
End | Go to last slide |
Number + Return | Go to specific slide |
b / m / f | Toggle blackout / mirrored / fullscreen mode |
c | Clone slideshow |
p | Toggle presenter mode |
s | Start & Stop the presentation timer |
t | Reset the presentation timer |
?, h | Toggle this help |
Esc | Back to slideshow |