Lecture 7
HTML
-
When we visit a URL, we’re requesting a file from a web server.
-
This file is written in HTML, or Hypertext Markup Language, which the browser is able to understand.
-
Instead of having functions, loops, or conditionals like a programming language, HTML is a markup language with tags.
- These tags tell the browser when to start doing something and when to stop doing something.
-
Let’s write some code inside
index.html
.<!DOCTYPE html> <html> <head> <title>hello, title</title> </head> <body> hello, body </body> </html>
-
<!DOCTYPE html>
indicates to the browser that this file is written in HTML. -
<html>
is a start tag or “open” tag, while</html>
is an end tag or “close” tag. -
In the
head
of our webpage, we have atitle
, or “hello, title”. -
In the
body
of our webpage, we have some text, or “hello, body”. -
We can open these in our browser, which are capable of interpreting these HTML tags line by line.
-
Opening
index.html
in our browser, we see this:
-
-
Let’s try creating multiple paragraphs in the body of our webpage.
-
Our browser ignores white spaces or tab keys, which are typically used in making code more readable. Instead, to create a line break between two paragraphs, we can use the
<br>
tag, indicating a line break. Note that this time, we don’t have to include a close tag since we can’t necessarily start breaking a line and end breaking a line—we are simply breaking a line.<!DOCTYPE html> <html> <head> <title>paragraphs</title> </head> <body> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam in tincidunt augue. Duis imperdiet, justo ac iaculis rhoncus, erat elit dignissim mi, eu interdum velit sapien nec risus. Praesent ullamcorper nibh at volutpat aliquam. Nam sed aliquam risus. Nulla rutrum nunc augue, in varius lacus commodo in. Ut tincidunt nisi a convallis consequat. Fusce sed pulvinar nulla. <br> Ut tempus rutrum arcu eget condimentum. Morbi elit ipsum, gravida faucibus sodales quis, varius at mi. Suspendisse id viverra lectus. Etiam dignissim interdum felis quis faucibus. Integer et vestibulum eros, non malesuada felis. </body> </html>
-
Opening this file in our browser, we see this:
-
-
To get a space between two paragraphs, we might surround each paragraph the
<p>
and</p>
tags, wherep
stands for paragraph.<!DOCTYPE html> <html> <head> <title>paragraphs</title> </head> <body> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam in tincidunt augue. Duis imperdiet, justo ac iaculis rhoncus, erat elit dignissim mi, eu interdum velit sapien nec risus. Praesent ullamcorper nibh at volutpat aliquam. Nam sed aliquam risus. Nulla rutrum nunc augue, in varius lacus commodo in. Ut tincidunt nisi a convallis consequat. Fusce sed pulvinar nulla. </p> <p> Ut tempus rutrum arcu eget condimentum. Morbi elit ipsum, gravida faucibus sodales quis, varius at mi. Suspendisse id viverra lectus. Etiam dignissim interdum felis quis faucibus. Integer et vestibulum eros, non malesuada felis. </p> </body> </html>
-
Opening this file in our browser, we see this:
-
Lists
-
To create an unordered list, we can use the tags
<ul>
and</ul>
to surround our list. To create an ordered list, we can use the tags<ol>
and</ol>
instead. -
For each list item, we can surround it with
<li>
and</li>
tags. -
Suppose we wanted an unordered list with foo, bar, and baz.
-
This is what our code might look like:
<!DOCTYPE html> <html> <head> <title>list</title> </head> <body> <ul> <li>foo</li> <li>bar</li> <li>baz</li> </ul> </body> </html>
-
Opening this file in our browser, we see this:
-
Note that with an ordered list, if we wanted to add or remove an item, we can simply add or delete a list item. The browser will take care of the numbering of each item for us.
Headings
-
In HTML, we can include some styling with heading tags.
-
We can surround text with heading tags:
<h1>
and</h1>
,<h2>
and</h2>
,<h3>
and</h3>
,<h4>
and</h4>
,<h5>
and</h5>
, and<h6>
and</h6>
. -
Let’s explore how each tag styles the text. Here is some code, and below is the output. We might note that as we go from
h1
toh6
, the text remains bold but becomes smaller and smaller.<!DOCTYPE html> <html> <head> <title>headings</title> </head> <body> <h1>One</h1> <h2>Two</h2> <h3>Three</h3> <h4>Four</h4> <h5>Five</h5> <h6>Six</h6> </body> </html>
-
Opening file in a browser, we see this:
Links
-
To link another webpage, say https://www.harvard.edu, on our webpage, we use
<a>
and</a>
tags, or anchor tags. Additionally, we must provide a reference, or the link we’d like to follow, and we can pass this in as an attribute of the anchor tag. -
Attributes modify the behavior of the tag it is passed into.
-
The attribute for providing a link is named
href
, so we pass in the key-value pair,href = "https://www.harvard.edu/"
, to the anchor tag. -
Our code might look like this:
<!DOCTYPE html> <html> <head> <title>link</title> </head> <body> Visit <a href="https://www.harvard.edu/">Harvard</a>. </body> </html>
-
Opening this file in our browser, we see this:
-
Note that within our anchor tags, we have the word “Harvard,” which users will click to access the link that we have specified.
-
Phishing can potentially occur via this construction, where Person A might try to “socially engineer” Person B to click a certain link. Person B believes that this link is taking them someplace, but actually, this link is taking them someplace else.
-
For example, if we had written
Visit <a href="https://www.harvard.edu/">PayPal.com</a>.
instead, the page would look like this: -
Upon clicking “PayPal.com,” we will actually be taken to www.harvard.edu.
-
Languages
-
In the beginning of the file, we have a tag that indicates the start of our HTML file, or
<html>
. We can pass in an attribute to this tag to specify the language of this file. This is particularly useful when a browser is attempting to translate a page, as it will know what language the page currently is in. -
For example, we could write
<html lang="en">
to specify that this webpage is in English.
Images
-
To include an image, we can use the
<img>
tag and pass in an attribute that specifies the image we would like. For example, if our image was named cat.jpg, we can pass in the key-value pairsrc="cat.jpg"
. -
Additionally, we can pass in another key-value pair that provides a placeholder for the image. To do this, we can add
alt="Grumpy Cat"
as an attribute of the<img>
tag. -
Our code might look like this:
<!DOCTYPE html> <html> <head> <title>image</title> </head> <body> <img alt="Grumpy Cat" src="cat.jpg"> </body> </html>
-
Opening this file in our browser, we see this:
Tables
-
To create a table in HTML, we first specify that we want a table using the
<table>
tags. Within the start and end of the table, we would like rows, which can be specified by<tr>
tags. Within the start and end of each row, we would like some data, which can be specified by<td>
tags. -
For example, to create a representation of a phone’s numberpad, we might write this code:
<!DOCTYPE html> <html> <head> <title>table</title> </head> <body> <table> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>4</td> <td>5</td> <td>6</td> </tr> <tr> <td>7</td> <td>8</td> <td>9</td> </tr> <tr> <td>*</td> <td>@</td> <td>#</td> </tr> </table> </body> </html>
-
Opening this file gives us this:
-
In the code for this table, there are many HTML elements, which include everything from a specific start tag to its end tag.
-
These HTML elements form a tree, and we can see this by looking at the indentations of the code.
-
Inside of the table element, there are 4 table row elements. If we consider the table element to be the node, then it has 4 children.
-
Inside each table row element are 3 table data elements. If we consider the table row element to be the node, then each has 3 children.
-
Document Object Model
-
A DOM, or document object model, is a tree with HTML elements.
-
For example, for the code on the left, we can draw the tree on the right.
-
At the top of this tree, we have
document
, which contains everything in the file. -
The only child of document is
html
.html
has two children,head
on the left andbody
on the right. -
Inside
head
, we see thetitle
element. However, inside thetitle
element, there are no elements, only a value. We’ve denoted this value with a different shape on the tree. Since thetitle
element does not contain any more elements, it is considered a leaf of this tree. -
Inside
body
, there are no elements, only the “hello, body” value. Thebody
element is also considered a leaf of this tree.
-
Forms
-
To create a form that can ask the user for information, we can use the
<form>
and</form>
tags. -
To ask the user for input inside these forms, we can use the
<input>
and</input>
tags. -
The
<input>
tag has many possible attributes:-
The
type
attribute specifies what type of input we want the user to provide. If the type istext
, then the user will be able to type into a box. If the type issubmit
, then the user will be able to click a button. -
The
placeholder
attribute specifies the text that will appear in an input box before user input. -
The
value
attribute specifies the text that will appear on the submit button.
-
-
Our code might look like this:
<!DOCTYPE html> <html> <head> <title>search</title> </head> <body> <form> <input placeholder="Query" type="text"> <input type="submit" value="Search"> </form> </body> </html>
-
Opening this file in a browser, we see this:
Querying With Google
-
We’ve built a front-end, where the user can interact with our website. However, when we click the “Search” button, since we have no back-end, nothing happens. We’ll use Google as our back-end instead of creating our own.
-
When we type in
https://www.google.com/search?q=cats
into the address bar, we’ll get a google search for “cats.”-
Taking a look at the formatting of this URL, we might note that in order to provide input from our browser to the server, we first visit some URL. Then, we append a question mark to that URL to indicate that some inputs are going to follow. Finally, we append key-value pairs separated by ampersands.
-
In this case, we have a URL, or
https://www.google.com/search
. Then, we append a question mark to gethttps://www.google.com/search?
. The key-value pair in this case isq=cats
, whereq
is the name of the input and cats is the user input. Combining these, we gethttps://www.google.com/search?q=cats
.
-
-
Let’s try to fix our “Search” button so that it returns a Google Search.
-
When the user submits our form, we want to go to that base URL, or https://www.google.com/search. We can write this in code by passing in an
action
attribute to the<form>
tag. -
We would also like to append the query to the end of that base URL. Thus, we need a key-value pair, where the key is the input name. To denote the input name, we can give that specific
<input>
tag aname
attribute, where the name is “q.” -
Our code might look like this:
<!DOCTYPE html> <html> <head> <title>search</title> </head> <body> <form action="https://www.google.com/search"> <input name="q" placeholder="Query" type="text"> <input type="submit" value="Search"> </form> </body> </html>
-
Additionally, we can add other attributes to the
<input>
tags. For example, we can turn autocomplete off to ensure that the user must type their query entirely each time. We can also set the box to autofocus, in which case the box is immediately selected upon loading the page. -
Our code might look like this:
<!DOCTYPE html> <html> <head> <title>search</title> </head> <body> <form action="https://www.google.com/search"> <input autocomplete="off" autofocus name="q" placeholder="Query" type="text"> <input type="submit" value="Search"> </form> </body> </html>
-
Opening this file in a browser, we see this:
CSS
-
There are many other tags in HTML. For example, we can indicate the header of a webpage with the
<header>
tag, the main portion of the webpage with the<main>
tag, and the footer of the webpage with the<footer>
tag.<!DOCTYPE html> <html> <head> <title>css</title> </head> <body> <header> John Harvard </header> <main> Welcome to my home page! </main> <footer> Copyright © John Harvard </footer> </body> </html>
- Note that
©
is an HTML entity. The computer recognizes this as the copyright symbol and displays that symbol on the webpage. The;
afterwards denotes the end of that HTML entity.
- Note that
-
Opening this file in a browser, we see this:
CSS in an Attribute
-
To introduce styling, such as positioning, sizes, fonts, and colors, we need another language, namely CSS, or Cascading Style Sheets.
-
If we want to change the style of a certain element, we can add an attribute to that element named
style
. Then, as the value, we can include styling, which follows a specific syntax. CSS requires that the styling syntax be a keyword (like “font-size”), a colon, and then a value (like “medium”). -
For example, we can change the
header
element to have a large font size by writing<header style="font-size: large">
. Similarly, we can change themain
element to have a medium font size, and thefooter
element to have a small font size. -
Additionally, if we want every HTML element within the
body
element to be centered, instead of adding that tag to each element withinbody
, we can simply addstyle="text-align: center"
to just the<body>
tag. This will affect all elements within thebody
element. -
Our code might look like this:
<!DOCTYPE html> <html> <head> <title>css</title> </head> <body style="text-align: center"> <header style="font-size: large"> John Harvard </header> <main style="font-size: medium"> Welcome to my home page! </main> <footer style="font-size: small"> Copyright © John Harvard </footer> </body> </html>
-
Opening this in a browser, we see this:
CSS in an HTML File
-
Note that our CSS and HTML languages are currently intertwined in the same lines. Typically, it is better practice to factor out one language and put it in a tag of its own. Thus, we will factor out the CSS and place all of the styling into
<style>
tags at thehead
of the file. -
Within the
<style>
tags, we need to specify the HTML elements that we are styling. -
Within each specified HTML element, we can specify the multiple style properties, each separated by semicolons.
-
Our code might look something like this:
<!DOCTYPE html> <html> <head> <style> body { text-align: center; } header { font-size: large; } main { font-size: medium; } footer { font-size: small; } </style> <title>css</title> </head> <body> <header> John Harvard </header> <main> Welcome to my home page! </main> <footer> Copyright © John Harvard </footer> </body> </html>
-
Opening this file in a browser will have the same result as including style tags in each HTML element.
-
Additionally, we can create classes, or collections of properties. For example, we can make a class named “centered”. Inside this class, we can include the property
text-align: center
. -
Now, for every HTML element that we want to have these properties, we can give them the attribute
class="centered"
. Since we can use these for multiple elements, classes are considered reusable. -
For our program, if we use classes instead, our code might look like this:
<!DOCTYPE html> <html> <head> <style> .centered { text-align: center; } .large { font-size: large; } .medium { font-size: medium; } .small { font-size: small; } </style> <title>css</title> </head> <body class="centered"> <header class="large"> John Harvard </header> <main class="medium"> Welcome to my home page! </main> <footer class="small"> Copyright © John Harvard </footer> </body> </html>
CSS in its Own File
-
We can also write the CSS in an entirely separate file. In this case, we must also tell our HTML file how to find its styling.
-
In a separate file called
css3.css
, we’ll have the same CSS as earlier..centered { text-align: center; } .large { font-size: large; } .medium { font-size: medium; } .small { font-size: small; }
-
In our HTML file, we can “link” the CSS file in the head by including this line:
<link href="css3.css" rel="stylesheet">
. -
This tag link tells the browser to link this HTML file to another file called
css3.css
. Therel="stylesheet"
part simply states that the relationship betweencss3.css
and our HTML file is thatcss3.css
is the style sheet.- The browser will copy-paste the contents of the CSS file as though it were at the top of the page.
-
We can reuse this CSS file by linking it to multiple HTML pages. Browsers exploit this property—if a browser realizes that a webpage we visit has the same CSS file as another, it will only download the file once.
-
This saves the user time because we no longer have to wait for the file to be downloaded.
-
This saves the website bandwidth because it doesn’t have to download the same file twice.
-
-
Our HTML file might look like this:
<!DOCTYPE html> <html> <head> <link href="css3.css" rel="stylesheet"> <title>css</title> </head> <body class="centered"> <header class="large"> John Harvard </header> <main class="medium"> Welcome to my home page! </main> <footer class="small"> Copyright © John Harvard </footer> </body> </html>
JavaScript
-
JavaScript is a programming language that allows for functions, conditions, boolean expressions, loops, and more.
-
JavaScript allows websites to be changed after a user has already downloaded it via the virtual HTTP envelope.
- For example, any time we receive a message in Gmail, we get a new row in the table of emails. We do not have to reload the webpage to see these updates.
-
How might the site change? After receiving some simple HTML page, the browser loads the HTML into memory via the DOM. With JavaScript, the DOM tree can evolve over time by asking some server, via HTTP, for the new data. Then, this new data can be presented to the user via an HTML element.
-
JavaScript can also listen for users’ input and provide some sort of response.
-
Some events JavaScript can listen for include blur, change, click, drag, focus, keypress, load, mousedown, mouseover, mouseup, submit, touchmove, and unload.
-
For example, when we’re surfing Google Maps, we might drag the map around. Each time we drag the map, new images appear. This occurs because each time we drag the map, the browser sends requests for more images and embeds them into the page.
-
Saying Hello
-
Suppose we want to create a webpage that has a user input their name and click a submit button. Then, the webpage should display an alert greeting the user with their name.
-
We can use a similar form as earlier—we’d like a text type input that has placeholder “Name” and a submit button. However, instead of searching on Google after submitting the form, we want to call a function that greets the user. To do this, we include
onsubmit="greet();"
as an attribute to our<form>
tag, wheregreet
is the function that greets the user. -
Now, we have to write the function
greet()
. This is written in JavaScript, so we’ll surround this function in<script>
tags. In this function, we have to recall the person’s name and display an alert.-
To recall the person’s name, we have to fetch the value they submitted. To do that, we need to identify the text box that they typed in. By providing the
<input>
tags another attribute calledid
, we can later uniquely identify that particular element. Thus, for the text type input, we can addid="name"
. -
To fetch that value, we can write
let name = document.querySelector('#name').value;
.-
let name =
assigns a value to the variablename
. -
querySelector()
is a function that searches for an element given a tag or an ID within thedocument
. -
#name
represents the element’sid
that we’re searching for. -
.value
extracts the user input in that field. -
Note that the
#
in#name
is required to indicate that thename
we’re searching for is anid
instead of a tag.
-
-
To display an alert, we can write
window.alert('hello, ' + name);
, wherewindow
is associated with the functionality of the browser window.
-
-
Finally, the default action the browser takes after the user submits a form is to reload the page. If we want to override the default action, we can write
return false;
after callinggreet();
. -
Our code might look like this:
<!DOCTYPE html> <html> <head> <script> function greet() { let name = document.querySelector('#name').value; window.alert('hello, ' + name); } </script> <title>hello</title> </head> <body> <form onsubmit="greet(); return false;"> <input autocomplete="off" autofocus id="name" placeholder="Name" type="text"> <input type="submit" value="Submit"> </form> </body> </html>
-
When opening this file in the browser and submitting the form with input “David,” we see this:
Changing Backgrounds
-
Using JavaScript, we can also change the aesthetics of a webpage.
-
Suppose we want to create a button that, when clicked, changes the background to red.
-
To create this button, we’ll use the
<button>
tags and write<button> id="red">R</button>
. Note that we’ve given the button anid
so we may select it in JavaScript later. -
Below this button, we can write a script that, when this button is clicked, changes the background to red. Note that this time, the script is below the code for the button because now, we would like the button to exist before the code executes.
-
In
<script>
tags, we’d like to listen for anonclick
event, particularly when the button is clicked. To do this, we can use theid
from earlier and writedocument.querySelector('#red').onclick
. -
When this button is clicked, a function should be called that changes the color of the background.
-
In JavaScript, we can create a function with no name and no parameters. In the function, we’d like to change the
backgroundColor
property of thebody
element’s style. -
Inside the function, we might write
document.querySelector('body').style.backgroundColor = 'red';
. -
The code in the
script
element might look like this:<script> document.querySelector('#red').onclick = function() { document.querySelector('body').style.backgroundColor = 'red'; }; </script>
-
-
Our code in its entirety might look like this:
<!DOCTYPE html> <html lang="en"> <head> <title>background</title> </head> <body> <button id="red">R</button> <script> document.querySelector('#red').onclick = function() { document.querySelector('body').style.backgroundColor = 'red'; }; </script> </body> </html>
-
After opening this file in our browser and clicking the button, we’ll see this:
-
We can also include more than just an “R” button. Maybe we want to include “G” and a “B” buttons too.
-
Our code might look like this:
<!DOCTYPE html> <html lang="en"> <head> <title>background</title> </head> <body> <button id="red">R</button> <button id="green">G</button> <button id="blue">B</button> <script> let body = document.querySelector('body'); document.querySelector('#red').onclick = function() { body.style.backgroundColor = 'red'; }; document.querySelector('#green').onclick = function() { body.style.backgroundColor = 'green'; }; document.querySelector('#blue').onclick = function() { body.style.backgroundColor = 'blue'; }; </script> </body> </html>
- Note that we factored out some code to another variable. Instead of repeatedly calling
document.querySelector('body')
, we stored that value in a variable calledbody
, and now, we have immediate access to that element.
- Note that we factored out some code to another variable. Instead of repeatedly calling
-
After opening this file and clicking the “B” button, we see this:
Changing Text Sizes
-
Suppose we wanted to create a website with these specifications:
-
A drop-down menu allows us to select a size from xx-small to xx-large. The default size is “initial”.
-
Upon picking a size, the text in the body of the webpage will change to this particular size.
-
-
For example, the webpage initially starts like this:
-
After selecting xx-large from the drop-down menu, the webpage displays this:
-
The code we write might look like this:
<!DOCTYPE html> <html lang="en"> <head> <title>size</title> </head> <body> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam in tincidunt augue. Duis imperdiet, justo ac iaculis rhoncus, erat elit dignissim mi, eu interdum velit sapien nec risus. Praesent ullamcorper nibh at volutpat aliquam. Nam sed aliquam risus. Nulla rutrum nunc augue, in varius lacus commodo in. Ut tincidunt nisi a convallis consequat. Fusce sed pulvinar nulla. </p> <select> <option value="xx-large">xx-large</option> <option value="x-large">x-large</option> <option value="large">large</option> <option selected value="initial">initial</option> <option value="small">small</option> <option value="x-small">x-small</option> <option value="xx-small">xx-small</option> </select> <script> document.querySelector('select').onchange = function() { document.querySelector('body').style.fontSize = this.value; } </script> </body> </html>
-
In this HTML file, we have some text and a dropdown menu of many sizes created with the
<select>
and<option>
tags. The default selected size is “initial.” -
In our
<script>
tags, we’re listening for changes in ourselect
element. Once there is a change, the font size of everything in thebody
element changes tothis.value
.this
is a placeholder for the variable that we currently have implicit access to. Since this code is associated with theselect
element,this.value
returns thevalue
of theselect
element.
Returning Location
-
To get someone’s current location, we might write this code:
<!DOCTYPE html> <html lang="en"> <head> <title>geolocation</title> </head> <body> <script> navigator.geolocation.getCurrentPosition(function(position) { document.write(position.coords.latitude + "," + position.coords.longitude); }); </script> </body> </html>
navigator.geolocation.getCurrentPosition
asks the browser to go into its navigator and get the user’s current position.- After the user’s current position is obtained, this anonymous (nameless) function is called that takes, as input, the user’s position.
document.write
prints to the screen. Using the position inputted into the function, it prints the coordinates of the latitude and longitude.
-
After opening this file in the browser and allowing the browser to know our location, we see this:
-
Searching this location on Google Maps, we find that we are at Langdell Hall!