Teaching team: Avand (avand@avandamiri.com), Rob (rob.m.gaston@gmail.com), Sandi (sandima.job@gmail.com).
To follow along, you'll need a Mapbox API access token. To get one, sign up for a Mapbox starter account (free) here
Leaflet is an excellent javascript mapping library that makes creating web maps super easy. To add Leaflet to your page, you'll need to add the following two tags:
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
GeoJSON is just a way of storing geographic data as JSON. It is widely used in the mapping community, and you'll find it all over the place if you look. Here's a path to a GeoJSON file that contains SF bicycle routes pulled from the venerable OpenStreetMap project (we'll put this on a map in class):
https://gist.githubusercontent.com/robgaston/dc5e5d709a0f1874a3b3/raw/ae107de9dc971abacf0cfa7a128c37fd3c38565a/sf_bike_routes.geojson
Media queries are how you can make your css rules "responsive" - that is, it can respond to differences in the way your user is viewing the page. Key to making pages mobile-friendly are the media queries max-width
and min-width
Here's an example of how you could include a stylesheet for use when the user's screen is small (i.e. a mobile device):
<link rel="stylesheet" media="(max-width: 600px)" href="mobile.css" />
Local storage is a convenient way to store data in a user's browser to retrieve the next time that user visits your page. To use it, we use a global object called localStorage
.
Items added to local storage are key value pairs. The values stored in local storage are strings, so if you need to store objects or arrays you should use JSON.stringify()
on them before adding them to local storage to store them as a string and use JSON.parse()
after getting the value to turn it back into an object.
Here is an example of how you could set and get data in local storage:
var fruits = ['apples','pears','oranges','kiwis'];
localStorage.setItem('fruits', JSON.stringify(fruits));
var storedFruits = JSON.parse(localStorage.getItem('fruits'));
jQuery is a powerful, widely used library that makes a lot of common practices in javascript web development a bit easier. Here are some examples of how you can use jQuery for some common things we've already done:
Vanilla JS | jQuery | |
---|---|---|
xhr | see get function below... | $.get(url, success); |
get element | var span = document.querySelector('span'); |
var span = $('span').first(); |
create element | var a = document.createElement('a'); |
var a = $('<a>'); |
add child | span.appendChild(a); |
span.append(a); |
get text | var linkText = a.textContent; |
var linkText = a.text(); |
set text | a.textContent = linkText; |
a.text(linkText); |
get attribute | a.getAttribute('href'); |
a.attr('href'); |
set attribute | a.setAttribute('href', 'http://wikipedia.org/'); |
a.attr('href', 'http://wikipedia.org/'); |
add event listener | a.addEventListener('click', function() { console.log('click') }; |
a.on('click', function() { console.log('click') }; |
The easiest way to add jQuery to your page is by adding the following script tag to your HTML (put this tag before your own scripts):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
XMLHttpRequest
(or XHR) is another javascript object that a browser provides. It is used for retrieving data from a URL for use in your code.
The following function uses XMLHttpRequest
to get data from a url and then passes the data to another function to handle on success:
function get(url, success) {
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function() {
if (xhr.readyState == 4 && xhr.status == 200) {
success(JSON.parse(xhr.response));
}
});
xhr.open("GET", url);
xhr.send();
}
The above code is handy for getting some data from a URL (for example, the Reddit JSON API) to do something with in your final project!
Conditionals are how we branch our code based on some condition in programming languages.
Often times, the condition in a conditional is based on a comparison of some values. In javascript, we use the following operators to compare values:
==
(or ===
): equal to!=
(or !==
): not equal to>
: greater than>=
: greater than or equal to<
: less than<=
: less than or equal toConditionals are simply blocks of code wrapped in some condition statement. If this statement is true
, then the code executes, otherwise it does not. They also provide a way to include alternative logic in an else
block. In javascript, they look something like this:
var a = 1;
var b = 2;
if (a === b) {
// this will NOT execute...:
alert('how could this be!?!?!');
} else {
// ...but this will execute:
alert('naturally...');
}
Comparisons return booleans. We can combine booleans using the &&
(and) and ||
(or) operators. The following tables show how these operators will combine different boolean values:
&& (and) |
true | false |
---|---|---|
true | returns true |
returns false |
false | returns false |
returns false |
|| (or) |
true | false |
---|---|---|
true | returns true |
returns true |
false | returns true |
returns false |
document.querySelectorAll
is another very useful function available in web browsers. This function can be used to get many items from the document based on a selector.
It works just like document.querySelector
, but instead of returning an Element
object, document.querySelectorAll
returns a NodeList
, which is functionally like an array of Element
objects (though it's actually its own object)
The following code shows an example of how you might get all the <li>
elements on the page and log their text content to the console:
var listItems = document.querySelectorAll('li');
for (var i = 0; i < listItems.length; i++) {
console.log(listItems[i].textContent);
}
When you attach an event handler to an event, it will be called with a special 'event' object as it's first argument (commonly named e
).
This object can be handy, for example, when attaching click events to anchor tags. In this case, you may not want to bypass the default behavior of an anchor tag (which is to follow the path in the anchor's href
attribute) and instead do something else. To achieve this, you can use a function available on this event object called preventDefault
like so:
// get the anchor element
var a = document.querySelector('a');
a.addEventListener('click', function(e) {
// prevent the link's default action
e.preventDefault();
// now do something else
alert('do something else!');
});
The event object has lots of other properties you may find interesting or useful, you can find a complete list at MDN
Objects are how we represent things in javascript. It turns out that everything in javascript is an object. For example, a string is an object with a property called length
that contains the length of the string as an integer. It's accessible like any other object property: myString.length
Here are some important JS objects that we've already worked with, peruse their many properties and methods at your leisure:
You won't ever need to know all of the methods and properties on these objects, but it's important to know where to find them when you begin to wonder "How do I do...?" As you use these objects, you'll learn the super useful ones really quickly. We're going to learn about another important javascript object next...
In javascript, when we want to store a list of things, we use an object called Array
. Arrays can be created in javascript using square braces ([
) like so: ['Avand', 'Rob', 'Sandi']
Like the other javascript objects we've looked at so far, Arrays have properties and methods that you'll probably find useful:
In javascript, when we want to execute some code some number of times, we use a for
loop. for
loops are particularly helpful for doing something with each item in an array.
For example, the following code will add a list item to a list for each item in the array instructors
:
var instructors = ['Avand', 'Rob', 'Sandi'];
var list = document.querySelector('ul');
var item;
for (var i = 0; i < instructors.length; i++) {
item = document.createElement('li');
item.textContent = instructors[i];
list.appendChild(item);
}
Objects are a very important data type in javascript. Objects can be stored in variables like other data types, and they themselves can contain more values as key value pairs. Here's an example of assigning an object to a variable:
var myPerson = {
firstName: null,
lastName:null
};
Object values can be accessed using a period (.
), like so:
console.log(myPerson.firstName);
Objects can even contain code in the form of functions. Here's an example of how you can add a function to the above object:
myPerson.getFullName = function() {
return this.firstName + ' ' + this.lastName;
};
this
in the above example is a very special variable in javascript. In this case it refers to the object myPerson because the function is attached to that object.
"DOM manipulation" is a term used to describe how we change a web page document using javascript. "DOM" stands for "Document Object Model", which really just refers to the page's document tree (something we've worked with a lot so far).
A browser tab always includes a few important objects that you'll need to know about in order to manipulate the DOM:
window
: this object represents the entire browser tab. It is the parent object of things we've already seen like alert
and prompt
document
: this object represents your html document. You'll use it to get elements from the page. It has some important functions:
element
: these objects (there's one for every element on your page) represent individual html elements. The above document functions (querySelector
and createElement
) return elements. Elements also include some properties and functions that you'll find useful:
Here's an example of how you could use the functions listed above to add a link to a page:
// get the body element
var body = document.querySelector('body');
// create an anchor element
var anchor = document.createElement('a');
// set the href and text of the anchor element
anchor.setAttribute('href', 'http://avandamiri.com/fewd-30/');
anchor.textContent = 'FEWD-30';
// add the anchor element to the body
body.appendChild(anchor);
Elements in a web page emit all kinds of "events", for example when a button is clicked it "fires" a "click" event. We can use these events to do things with special javascript functions called event handlers.
Event handlers, which are just javascript functions to be called on some event, can be connected to events using a function on element objects called addEventListener
.
For example, you can create an event handler for button clicks that alerts a message like so:
// get the button element
var button = document.querySelector('button');
// create an event handler
function buttonClicked() {
alert('Hello World!');
}
// add your event listener
button.addEventListener('click', buttonClicked);
A 'clearfix' is a hack used to manage layouts with floats, see this example. The modern way to do this is with the CSS property overflow:auto;
Forms are how we manage data we are going to send to the server. The entire form content is wrapped in a <form>
tag. Forms have attributes that describe how they should interact with the server - the most important of these are method
(which describes the HTTP method to use) and action
(which describes where the data should be sent). See MDN's form reference for a complete list and more details
The form's data are stored in <input>
tags to allow for user interaction. There are many types of <input>
tags and related attributes, see MDN's reference on inputs for a comprehensive list of input types and other related input attributes.
<input>
tags are labeled by <label>
tags. You can use the for
attribute on your <label>
tag to reference the labeled input element's id.
In programming languages, information is stored in things called variables.
in Javascript variables are created using the keyword var
. For example: var x = 1;
Variables can store different types of data, for example:
In the above example (var x = 1;
), we call the equals sign (=
) the "operator". The operator =
assigns a value to a variable. The above example assigns the value 1
to the variable x
.
There are other operators used to manipulate values, for example: +
, -
, *
, etc.
Functions fundamentally have three parts:
undefined
.For example:
function sum(a, b) {
var result = a + b;
return result;
}
Functions are called with parentheses, for example, the following returns the number 5:
sum(2, 3);
Javascript and the browser provide you with a bunch of functions you can use to do things. You can find a complete list at MDN. Some examples (try them out!):
parseInt
alert
prompt
;
)var
.forExample
Build more pages for Acme Anvil Corporation. Designs for the pages are provided in the assignment.
CSS selectors are how you get things on the page to style them in your CSS. There are a few basic ways to do this:
a {color: red;}
.danger {color: red;}
#warning-message {color: red;}
When it comes to ids and classes, remember:
Select on multiple things on a single element by chaining selectors together without a space, for example: a.danger.btn {color: red;}
You can select nested elements by putting a space between selectors. For example: header a
selects all the <a>
tags in the header.
Some rules of thumb when nesting CSS selectors:
Pseudo-selectors allow you to create CSS selectors that select elements based on a particular state of that element (called pseudo-classes). They are denoted by a colon. For example: a:hover
selects the <a>
tags that are currently being hovered over by the cursor.
A list of all the available pseudo-classes is available on MDN.
Some rules of thumb when using pseudo-selectors:
The way we've managed CSS layouts has evolved over the years. In chronological order:
<table>
tag, you can create columns and rows. This (sort of) allows you to manage complex layouts, but it's really clunky and has some limitationsfloat:left;
or float:right;
pulls elements out of the layout flow. This has been used to create column layouts, but floating has some idiosyncrasies that require proactive management. Floated elements must be "cleared", and this can cause problems.display:flex;
is the modern way to manage complex layouts with CSS. It allows you to flexibly size child elements using some special CSS properties such as flex
. You can find more info at MDN.There are 3 ways to set child width when using display:flex;
:
px
using the width
propertyflex
property. Elements with a flex
value will get a proportion of the entire remaining width of the parent element based on the ratio of it's flex value to those of all other child elements with a flex
property
Build the homepage for Acme Anvil Corporation. Design for the page is provided in the assignment.
Remember to push your work to GitHub then submit a link to your page on Schoology.
There are a bunch of things that make up a web page aside from the actual document content itself. Stuff like...
Generally speaking, metadata goes in the <head>
tag, and page content goes in the <body>
tag.
style
attribute. In most cases, this is the wrong way to style your web page, but can be handy for testing things out.
example: <footer style="text-align:center;"></footer>
<style>
tag. This can work for small pages, but is usually not preferred.
example: <style>footer { text-align:center; }</style>
<link>
tag. This is usually the best thing to do as it separates your style completely from your markup.
example: <link rel="stylesheet" href="styles.css">
IMPORTANT NOTE! Inline styles take precedence over styling rules. Still, you probably shouldn't use them.
When you use anything other that "static" (the default value for position), you'll be able to use the properties "top", "right", "bottom" and "left" to adjust your elements position, but how it is positioned depends on what value you set position to:
position: static;
positions based on the content; cannot be adjusted and it's the default value for position for all elements (you probably don't need to know that, but can use it to sound cool at parties)
position: relative;
positions relative to where it normally is
position: absolute;
like "fixed", but positions with respect to the element's nearest relative container
position: fixed;
positions with respect to the browser window (useful for sticky headers and stuff)
Some things to remember:
homework-1.html
http://{ your user name }.github.io/{ your repo name }/homework-1.html
Here's some you'll probably use a lot:
http://{ your user name }.github.io/{ your repository name }/
for example: http://avand.github.io/fewd-30/
Application | Command | Result |
---|---|---|
Atom | Command + Right Arrow | Move cursor to the end of a line |
Atom | Command + Left Arrow | Move cursor to the end of a line |
Atom | Option + Right Arrow | Move cursor to the end of next word |
Atom | Option + Left Arrow | Move cursor to the beginning of previous word |
Atom | Command + N | New file |
Atom | Command + S | Save current file |
Atom | Command + D | Multi-select |
Atom | Command + Enter | Add a new line below the current line |
Chrome | Command + R | Refresh Page |
Chrome | Command + Option + I | Open Developer Tools |
Chrome | Control + Tab | Switch tab (forward) |
Chrome | Control + Shift + Tab | Switch tab (backward) |
Mac | Command + Control + Space | EMOJIS!!!!!!!!πππππ |
Mac | Command + Tab | Switch programs |
Mac | Command + ` | Switch windows within a program |
Mac | Command + Shift + 4 | Take a screenshot (saved to desktop) and... free ruler! |
For more keyboard shortcuts: click here.
Student | repo link | gh-pages link |
---|---|---|
Dave | repo | github pages |
Arjun | repo | github pages |
Yana | repo | github pages |
Lila | repo | github pages |
Celso | repo | github pages |
Jeanne | repo | github pages |
Angela | repo | github pages |
Fernanda | repo | github pages |
Kristin | repo | github pages |
Alfredo | repo | github pages |
Stephanie | repo | github pages |
Lindsey | repo | github pages |
Wenjia | repo | github pages |
Maks | repo | github pages |
Gregory | repo | github pages |
Roman | repo | github pages |
Kaitlin | repo | github pages |
jakub | repo | github pages |