Lecture 6 JavaScript
Lecture 6 JavaScript
Lecture 6
JavaScript
Outline
Part 1 Part 2
• Introduction • DOM Manipulation
• Variables • Intervals
• querySelector
• Local Storage
• Conditions
• APIs
• DOM Manipulation
• JavaScript Objects
JavaScript Console
• Currency Exchange
Part 1
Introduction
• So far, we’ve discussed how to build simple web pages using HTML and CSS, and how to use Git and
GitHub in order to keep track of changes to our code and collaborate with others. We also familiarized
ourselves with the Python programming language, started using Django to create web applications, and
learned how to use Django models to store information in our sites.
• Today, we’ll introduce a new programming language: JavaScript.
JavaScript
• Recall that in most online interactions, we have a client/user that sends an HTTP Request to a
server, which sends back an HTTP Response.
• All of the Python code we’ve written so far using Django has been running on a server
• JavaScript will allow us to run code on the client side, meaning no interaction with the server
is necessary while it’s running, allowing our websites to become much more interactive.
JavaScript
• In order to add some JavaScript to our page, we can add a pair of <script> tags somewhere in
our HTML page.
• We use <script> tags to signal to the browser that anything we write in between the two tags is
JavaScript code we wish to execute when a user visits our site.
• Our first program might look something like this:
JavaScript
• The alert function in JavaScript displays a message to the user which they can then dismiss.
• To show where this would fit into an actual HTML document, here’s an example of a simple page
with some JavaScript:
JavaScript - Event
• Let’s begin by turning our JavaScript from before into a function called hello:
• These changes allow us to wait to run parts of our JavaScript code until a certain event occurs.
JavaScript - Variables
• JavaScript is a programming language just like Python, C, or any other language you’ve worked
with before, meaning it has many of the same features as other languages including variables.
• There are three keywords we can use to assign values in JavaScript:
var: used to define a variable globally.
let: used to define a variable that is limited in scope to the current block such as a function
or loop.
• For an example of how we can use a variable, let’s take a look at a page that keeps track of a
counter:
JavaScript – querySelector
• To extract a heading. Then, to manipulate the element we’ve recently found, we can change
its innerHTML property:
JavaScript – querySelector - Conditions
Notes:
• Queryselector returns An Element object representing the first element in the document that
matches the specified set of CSS selectors, or null is returned if there are no matches.
• If you need a list of all elements matching the specified selectors, you should
use document.querySelectorAll() instead.
• You can get the first element with class="example” by using
document.querySelector(".example");
• For Example, you can get the first <p> element with class="example" by using
document.querySelector("p.example");
• You can get the first <a> element that has a "target" attribute by using
document.querySelector("a[target]");
JavaScript - DOM Manipulation
• Let’s use this idea of DOM manipulation to improve our counter page:
JavaScript - DOM Manipulation
• We can make this page even more interesting by displaying an alert every time the counter
gets to a multiple of ten.
• In this alert, we’ll want to format a string to customize the message, which in JavaScript we
can do using template literals.
• Template literals require that there are backticks (`) around the entire expression and a $ and
curly braces around any substitutions. For example, let’s change our count function:
JavaScript - DOM Manipulation
• Now, let’s look at some ways in which we can improve the design of this page.
• First, just as we try to avoid in-line styling with CSS, we want to avoid in-line JavaScript as
much as possible.
• We can do this in our counter example by adding a line of script that changes the onclick
attribute of a button on the page, and removing the onclick attribute from within the button
tag.
JavaScript - DOM Manipulation
• One thing to notice about what we’ve just done is that we’re not calling the count function by
adding parentheses afterward, but instead just naming the function.
• This specifies that we only wish to call this function when the button is clicked.
• This works because, like Python, JavaScript supports functional programming, so functions
can be treated as values themselves.
• The above change alone is not enough though, as we can see by inspecting the page and
looking at our browser’s console:
JavaScript - DOM Manipulation
• This error came up because when JavaScript searched for an element using
document.querySelector('button’) , it didn’t find anything.
• This is because it takes a small bit of time for the page to load, and our JavaScript code ran
before the button had been rendered.
• To account for this, we can specify that code will run only after the page has loaded using the
addEventListener function.
• This function takes in two arguments:
1) An event to listen for (e.g.: 'click')
2) A function to run when the event is detected (eg: hello from above)
JavaScript - DOM Manipulation
• We can use the function to only run the code once all content has loaded:
• In the example above, we’ve used an anonymous function, which is a function that is never
given a name.
JavaScript - DOM Manipulation
• Putting all of this together, our JavaScript now looks like this:
JavaScript - DOM Manipulation
• Another way that we can improve our design is by moving our JavaScript into a separate file.
The way we do this is very similar to how we put our CSS in a separate file for styling:
• Write all of your JavaScript code in a separate file ending in .js, maybe index.js.
• Add a src attribute to the <script> tag that points to this new file.
• For our counter page, we could have a file called counter.html and a file called counter.js
that looks like the following:
JavaScript - DOM Manipulation
Let’s get started on another example of a page that can be a bit more interactive.
Below, we’ll create a page where a user can type in their name to get a custom greeting.
JavaScript - DOM Manipulation
• We can do more than just add HTML to our page using JavaScript, we can also change the
styling of a page!
• In the page below, we use buttons to change the color of our heading.
JavaScript - DOM Manipulation
The console is a useful tool for testing out small bits of code and debugging. You can write and
run JavaScript code in the console, which can be found by inspecting element in your web
browser and then clicking console. (The exact process may change from browser to browser.) One
useful tool for debugging is printing to the console, which you can do using the console.log
function.
For example, in the colors.html page above, I can add the following line:
• In addition to the traditional function notation we’ve seen already, JavaScript now gives us
the ability to use Arrow Functions where we have an input (or parentheses when there’s no
input) followed by => followed by some code to be run.
• For example, we can alter our script above to use an anonymous arrow function:
JavaScript - Arrow Functions
• We can also have named functions that use arrows, as in this rewriting of the count function:
JavaScript - DOM Manipulation
• To get an idea about some other events we can use, let’s see how we can implement our color switcher
using a dropdown menu instead of three separate buttons. We can detect changes in a select element
using the onchange attribute.
• In JavaScript, this is a keyword that changes based on the context in which it’s used. In the case of an
event handler, this refers to the object that triggered the event.
JavaScript - TODO List
• To put together a few of the things we’ve learned in this lecture, let’s work on making a TODO list entirely
in JavaScript.
We’ll start by writing the HTML layout of the page.
Notice below how we leave space for an unorderd list, but we don't yet add anything to it.
Also notice that we add a link to tasks.js where we’ll write our JavaScript.
JavaScript - TODO List
1) Here, we only query for our submit button and input task field
once in the beginning and store those two values in the
variables submit and newTask.
2) We can enable/disable a button by setting its disabled
attribute to false/true.
3) In JavaScript, we use .length to find the length of objects such
as strings and arrays.
4) At the end of the script, we add the line return false. This
prevents the default submission of the form which involves
either reloading the current page or redirecting to a new one.
5) In JavaScript, we can create HTML elements using the
createElement function. We can then add those elements to
the DOM using the append function.
JavaScript - TODO List
JavaScript - Intervals
• In addition to specifying that functions run when an event is triggered, we can also set functions
to run after a set amount of time.
• For example, let’s return to our counter page’s script, and add an interval so even if the user
doesn’t click anything, the counter increments every second.
• To do this, we use the setInterval function, which takes as argument a function to be run, and
a time (in milliseconds) between function runs.
• The setInterval() method continues calling the function until clearInterval() is called, or the
window is closed.
JavaScript - Intervals
JavaScript - Local Storage
• One thing to notice about all of our sites so far is that every time we reload the page, all of our
information is lost. The heading color goes back to black, the counter goes back to 0, and all of the tasks
are erased. Sometimes this is what we intend, but other time’s we’ll want to be able to store information
that we can use when a user returns to the site.
• One way we can do this is by using Local Storage, or storing information on the user’s web browser
that we can access later.
• This information is stored as a set of key-value pairs, almost like a Python dictionary. In order to use
local storage, we’ll employ two key functions:
• localStorage.getItem(key) : This function searches for an entry in local storage with a given key, and
returns the value associated with that key.
• localStorage.setItem(key, value) : This function sets an entry in local storage, associating the key
with a new value.
JavaScript - Local Storage
• Let’s look at how we can use these new functions to update our counter! In the code below,
JavaScript - APIs
JavaScript Objects
• A JavaScript Object is very similar to a Python dictionary, as it allows us to store key-value pairs. For
example, I could create a JavaScript Object representing Harry Potter:
• You can then access or change parts of this object using either bracket or dot notation:
JavaScript - APIs
• One way in which JavaScript Objects are really useful is in transferring data from one site to another, particularly when
using APIs.
• An API, or Application Programming Interface, is a structured form of communication between two different
applications.
• For example, we may want our application to get information from Google Maps, Amazon, or some weather service. We
can do this by making calls to a service’s API, which will return structured data to us, often in JSON (JavaScript
Object Notation) form.
• For example, a flight in JSON form might look like this:
• The values within a JSON do not have to just be strings and numbers as in the example above. We can also store lists,
or even other JavaScript Objects:
JavaScript - Currency Exchange
• To show how we can use APIs in our applications, let’s work on building an application where we can find
exchange rates between two currencies.
• Throughout the exercise, we’ll be using the European Central Bank’s Exchange Rate API. By visiting their
website, you’ll see the API’s documentation, which is generally a good place to start when you wish to use
an API.
• We can test this API by visiting the URL: https://open.er-api.com/v6/latest/USD.
• When you visit this page, you’ll see the exchange rate between the U.S. Dollar and many other currencies,
written in JSON form.
• You can also change the GET parameter in the URL from USD to any other currency code to change the
rates you get.
JavaScript - Currency Exchange
• Let’s take a look at how to implement this API into an application by creating a new HTML file called
currency.html and link it to a JavaScript file but leave the body empty:
• Now, we’ll use something called AJAX, or Asynchronous JavaScript And XML, which allows us to access
information from external pages even after our page has loaded.
• In order to do this, we’ll use the fetch function which will allow us to send an HTTP request.
• The fetch function returns a promise. We won’t talk about the details of what a promise is here, but we can
think of it as a value that will come through at some point, but not necessarily right away. We deal with
promises by giving them a .then attribute describing what should be done when we get a response. The
code snippet below will log our response to the console.
JavaScript - Currency Exchange
https://open.er-api.com/v6/latest/USD
• One important point about the above code is that the argument of .then is always a function. Although it
seems we are creating the variables response and data, those variables are just the parameters of two
anonymous functions.
JavaScript - Currency Exchange
• Rather than simply logging this data, we can use JavaScript to display a message to the screen, as in the
code below:
https://open.er-api.com/v6/latest/USD
JavaScript - Currency Exchange
• Now, let’s make the site a bit more interactive by allowing the user to choose which currency they would
like to see. We’ll start by altering our HTML to allow the user to input a currency:
JavaScript - Currency Exchange
• Now, we’ll make some changes to our JavaScript so it only changes when the form is submitted, and so it takes into
account the user’s input. We’ll also add some error checking here:
https://open.er-api.com/v6/latest/USD
JavaScript - Currency Exchange
• That’s all for this lecture! Next time, we’ll work on using JavaScript to create even more engaging user interfaces!