HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
///////////////////////////////// Reading JSON with Fetch API ////////////////////////////////
/*
The JSON code we've practiced thus var has been very simple. JSON is capable of holding much more data than we've been storing in our JSON objects.
In fact, depending on the data, JSON files can end up holding hundreds of objects
From this point on, the JSON data we will use will be contained within a JSON file rather than hard coding the JSON objects into our JavaScript code.
JSON data within a JSON file may at first look different than the JSON code we've seen here, but don't get confused
.json files wrap the entirety of the JSON content within a pair of curly brackets { } as you will see
.json files also almost always contain multiple objects, but the syntax for this is something we've already seen, so don't get intimidated.
You may be curious as to why we would want to store all of these objects in the same JSON file
This is because JSON is extremely useful for presenting data in an organized, clean format that is easy for both humans and machines to read
Say, for example, we were creating a JSON file that stored all of the books in our own personal library.
Instead of having 30 or so individual variables storing the data, we can organize the data in a JSON file by placing them within an array
Each element of the array is a JSON object itself, and the elements are separated by commas, just like a JavaScript array
Remember that in JSON, the elements of arrays are contained within a pair of square brackets [ ] and objects are placed within curly brackets { }
Here is an example of using JSON to bookkeep a personal library: https://lsu-ddem.github.io/ddem-coding-support/json/my-library.json
You can see the data organized in an easily readable format, representing our library of 3 books
Now what we can do with the JSON file representing our library is read it and store the data in our JavaScript code, and later display it using HTML
There are multiple ways to access and read a JSON data file hosted online, and use the data in JavaScript
Fetch API is one of the most user friendly approaches
///////Fetch API:
Fetch API provides an interface for fetching resources. We can use it to access JSON data from anywhere on the web, and use it in our code.
The fetch method has a single mandatory parameter, which is the URL of the resource we want to access or 'fetch'
The fetch method returns something called a Promise, which is the response of the request we sent (whether or not it was successful)
A Promise also contains various information about the request and response, such as headers and the HTTP status, but we won't be concerned with this data for now
After the response is retrieved, we can specify what the code should do by programming the .then() method.
Before we can program what we want to do with the data returned, we have to actually extract the data from the Promise we recieve back.
To extract the content from the HTTP Response, we format the response of the fetch to a specified type.
The .then() method is used in Fetch API to specify the response type of the promise, and also to program what we want to do with the data
To format the data we get back into a specific data type, the then() method takes the response of the fetch (which is a promise) as a parameter, and passes the promise into a function which extracts the data (removing the extra information such as headers, http status, etc) and parses it into the specified data type.
Data can be extracted from a promise and returned in the following formats:
.arrayBuffer() , .blob() , .json() , .text() , and .formData()
Since we're working with JSON, we can specify that we want the data transformed into JSON like so:
*/
// we'll use our simple library JSON data from the sections before to walk through our first fetch example, then we'll practice with larger data sets:
fetch("https://lsu-ddem.github.io/ddem-coding-support/json/my-library.json")
// remember that the first step is using the fetch method to 'fetch' the url we want to access.
// remember we will implement the .then() twice: once to specify the return type of the data, to format it into JSON, and the second time to program what we want to do with the formatted data.
// our first .then() method contains a shorthand JavaScript function that parses the response into JSON
.then(res => res.json())
/* Sidenote:
The shorthand function (also known as an arrow function) is simply a compacted JavaScript function,
where, in this case, res is the parameter taken in by the function (which is the response from our fetch request), and res.json() is the output of the function, which parses the promise returned to us into JSON data
this shorthand function: .then(res => res.json()) is the exact same as the longer version below:
.then(function(res) {
return res.json();
}
*/
// The next then() method is where we actually work with the JSON data we extracted.
// The second .then() takes the response of the first then method as a parameter
// Here we can do whatever we please with the JSON data, such as printing it to the console, saving it to arrays or variables, displaying it in HTML, etc.
.then(out => {
// This is another arrow function, it is the exact equivalent of saying .then(function(out){ })
// Here we're simply saying to print the output of the response that was parsed into JSON to the console
console.log("Output: ", out);
// If you look at the console, you'll see that our entire myLibrary object was printed to the console as a JSON object
})
.catch(err => console.error(err));
// This line closes the function and closes the parenthesis containing the parameter to the second then method, and implements the .catch() method, which prints the error message to the console in the event of an error
/*
Now lets look at working with the data we get in return in more detail than just printing the entire JSON to the console
*/
// Lets write a script to print the titles of all of the books within our library and the authors name in this format: 'Title by Author' :
fetch("https://codepen.io/lsuddem/pen/pGNzQy.js")
.then(res => res.json())
.then(out => {
// Each line before this one should be familiar to you;
// line 89 fetches the JSON data storing our library
// line 90 parses the response object into JSON
// and finally line 91 creates a shorthand function for the response from the fetch,
// The next few lines are the contents of the function handling the JSON data parsed from the response from the fetch
console.log("Books in my Library:");
// this for loop loops through the object within the myLibrary object (remember that there are multiple objects within the myLibrary object to represent our books)
for (let i = 0; i < out.myLibrary.length; i++) {
// the loop iterates as many times as there are objects(aka for as many books as there are) within myLibrary by setting the condition to the length of the myLibrary object
console.log(out.myLibrary[i].title + " by " + out.myLibrary[i].author);
// we then simply print the title and author of each book by accessing the title and author keys of the current object the loop is on using dot notation
}
});
// Before we use Fetch API with actual JSON data, lets practice the library scenario with your own JSON data
// First, you'll need to create your own JSON data representing your library of books.
// There are many methods to go about creating a JSON file or hosting the JSON file online
// For example, http://myjson.com/ is convenient to use, but since you already have experience with codepen, you can just store JSON data in a new pen
// To store JSON data in a codepen to be used from another script later on, first create a new pen in a new tab
// Next, simply write the JSON data in the JavaScript section of the codepen editor, heres an example : https://codepen.io/lsuddem/pen/pGNzQy
// To reference the JSON data in a Fetch or XMLHTTPRequest, simply set the url parameter to the url of the pen and add '.js' to the end of the link
// So if the pen storing my library is https://codepen.io/lsuddem/pen/pGNzQy, I can fetch the JSON data by using https://codepen.io/lsuddem/pen/pGNzQy.js as the url
// Try it!
// First create your pen containing the JSON data representing your own library, or just some of your favorite books.
// Include at least 5 books, with key:value pairs for their Title, Author, Rating (on scale of 0-5), and anything else you wish to include
// In the space below, create a new fetch using the url to your own JSON data
// parse the response from the fetch into JSON and loop through your data, printing it to the console in this format:
// Books in my library: (or "My favorite books:")
// Title by Author : i star rating ; where i is the rating you gave the book in the JSON data
/*
After you've successfully printed your books to the console, lets practice using Fetch API with some real data
Many web services and APIs often use JSON to format data that is available to the public.
For example, many local governments are working towards transparency by providing easily accessible data to the public in the form of open data websites, such as https://data.brla.gov/
According to Forbes, as of 2019 there are over 90 cities with such open data portals, including Austin, Chicago, Dallas, Las Vegas, NYC, Memphis, etc. : https://www.forbes.com/sites/metabrown/2018/04/29/city-governments-making-public-data-easier-to-get-90-municipal-open-data-portals/#6969d3c5a0d7
For this section, I'll use Baton Rouge's open data, but it would be good practice to try fetching and manipulating JSON data from other cities' open data portals afterwards
So far we've become experts at fetching JSON data and printing specific key:value pairs from the response we receive
Next we'll gain experience working with larger data sets and doing more with the data
Let's say you currently live in Baton Rouge, but you're considering moving to another city.
You really like the food in Baton Rouge, however, so you're reluctant about leaving the city, but the crime in Baton Rouge is a main factor driving you to move elsewhere
Before you look at other cities and their crime statistics, you first decide to do some quick calculations regarding the crime in Baton Rouge
You visit Baton Rouge's open data resource, https://data.brla.gov, and view the different categories of crime within Public Safety (https://data.brla.gov/Public-Safety/Baton-Rouge-Crime-Incidents/fabb-cnnu)
Looking at a visualization of the data, you see that crimes are categorized into 12 main classifications: crimes related to theft, narcoticts, battery, criminal damage to property, vehicle burglary, assault, residential burglary, firearm, non-residential burglary, individual robbery, nuisance, and other
Let's say, for whatever reason, the crimes you're most concerned with include residential burglary, firearm, individual robbery, and narcotics. Perhaps you're immune to the other types of crimes, who knows. But these 4 crimes, you just can't stand to be around.
From the large set of crime data provided by data.brla.gov, lets tally each of the crimes recorded pertaining to these 4 specified categories, and print the totals of each type of crime committed in Baton Rouge to the console:
*/
// first we'll create a new fetch to the JSON data representing the record of crimes in Baton Rouge
fetch("https://data.brla.gov/resource/5rji-ddnu.json")
// next we parse the response from the fetch into JSON
.then(res => res.json())
// now we program the counting of each of the 4 types of crimes we're concerned with
.then(out => {
// the next four lines simply declare the variables that will store the totals for each of the types of crimes
let totalResidentialBurglary = 0;
let totalFirearm = 0;
let totalIndivRobbery = 0;
let totalNarcotics = 0;
// the for loop on the next line loops through the output of the parsed JSON data
for (let i = 0; i < out.length; i++) {
// the next few if statements check if the current object's crime key:value pair matches that of the four types of crimes we're concerned with in this scenario
// because the data set stores the crime types in capital letters, the types have to be in caps when we check if the crime is equal to any of the four types, because lowercase letters do not equate to capital letters, like so:
if (out[i].crime == "RESIDENTIAL BURGLARY") {totalResidentialBurglary++};
if (out[i].crime == "FIREARM") {totalFirearm++};
if (out[i].crime == "INDIVIDUAL ROBBERY") {totalIndivRobbery++};
if (out[i].crime == "NARCOTICS") {totalNarcotics++};
}
// now we'll print the tallied counts to the console
console.log(
"Total Residential Burglary Crimes Committed : " +
totalResidentialBurglary
);
console.log("Total Firearm Crimes Committed : " + totalFirearm);
console.log(
"Total Individual Robbery Crimes Committed : " + totalIndivRobbery
);
console.log(
"Total Narcotics Crimes Committed : " + totalResidentialBurglary
);
// looking at the console, you can see the totals for each of the categories of crime
});
// Lets say that living in Baton Rouge your entire life has made you somewhat unphased when you see the totaled numbers for the four types of crimes, and these results don't necessarily persuade you to move
// You decide, instead, that if the total number of crimes on your street exceeds 30, you'll condsider moving to another town
// You live on a street called Government, so in your new fetch you're going to tally all of the crimes that occured on government street like so:
fetch("https://data.brla.gov/resource/5rji-ddnu.json")
.then(res => res.json())
.then(out => {
let totalCrimeCount = 0;
for (let i = 0; i < out.length; i++) {
// the data set inludes a key specifically for the street name (st_name), as well as a key for the entire address
if (out[i].st_name == "GOVERNMENT") {totalCrimeCount++};
}
console.log(
"There were " +
totalCrimeCount +
" crimes documented on government street in 2018 "
);
});
// Okay, as of now the crime count is only at a mere 14 offenses, so you decide you'll stick around and keep eating southern food for a while longer.
// Thats the gist of Fetch API!
///////////////////////// Exercises /////////////////////////
// 1: You want to move to a new subdivision in East Baton Rouge that is smaller than your current big neighborhood.
// Create a new fetch to the data set provided below which contains information about all of the subdivisions in East Baton Rouge
// You're interested in subdivisions with no more than 25 lots total.
// Print the names of your options to the console (print the subdivision names with 25 or less lots) in this format: Subdivision Name has ___ lots
// https://data.brla.gov/resource/px43-apna.json
// 2: You're visiting Dallas for the weekend and you have a friend who works in the government and can get you into any of the cultural centers in Dallas to see a performance
// Conveniently, there exists a database on Dallas's open data portal containing information regarding all of your options
// Use fetch API to print your options to the console to decide which cultural center to visit
// Print the information of each cultural center in this format:
// Center Name : Phone Number
// Center Address
// Center Description xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// https://www.dallasopendata.com/resource/g7b4-vh2w.json
Also see: Tab Triggers