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.
<body class="sticky-footer">
<header>
<h1>The Can Store</h1>
</header>
<div class="sticky-footer__grow l-with-sidebar-left">
<aside>
<search>
<form>
<div>
<label for="category">Choose a category:</label>
<select id="category">
<option selected>All</option>
<option>Vegetables</option>
<option>Meat</option>
<option>Soup</option>
</select>
</div>
<div class="form-search">
<label for="searchTerm">Enter search term:</label>
<input type="text" id="searchTerm" placeholder="e.g. beans">
</div>
<button type="submit">Filter results</button>
</form>
</search>
</aside>
<main></main>
</div>
<footer>
<p>All icons found at the Noun Project:</p>
<ul>
<li>Bean can icon by <a href="https://thenounproject.com/yalanis/" rel="external noopener">Yazmin Alanis</a>.</li>
<li>Vegetable icon by <a href="https://thenounproject.com/skatakila/" rel="external noopener">Ricardo Moreira</a>.</li>
<li>Soup icon by <a href="https://thenounproject.com/ArtZ91/" rel="external noopener">Arthur Shlain</a>.</li>
<li>Meat Chunk icon by <a href="https://thenounproject.com/smashicons/" rel="external noopener">Oliviu Stoian</a>.</li>
</ul>
</footer>
</body>
@import "https://germanfrelo.github.io/base-css-stylesheet/base.css" layer(base);
@import "https://codepen.io/germanfrelo/pen/mdMYKza.css" layer(styles);
@import "https://fonts.googleapis.com/css2?family=Cherry+Swash:wght@400;700&family=Raleway:wght@700;800&display=swap";
:root {
--ff-sans: "Raleway", sans-serif;
--c-tx-1: hsl(210deg 100% 15%);
--c-tx-2: hsl(210deg 100% 15%);
--c-bg-1: hsl(60deg 100% 75%);
--c-bg-2: hsl(60deg 100% 75%);
--c-bg-3: hsl(60deg 100% 75%);
--c-bd-1: hsl(210deg 100% 15%);
}
@media (prefers-color-scheme: dark) {
:root {
--c-tx-1: hsl(210deg 100% 15%);
--c-tx-2: hsl(210deg 100% 15%);
}
}
h1,
h2 {
font-family: "Cherry Swash", cursive;
font-weight: 700;
}
h1 {
padding-inline: 1em;
line-height: 1;
text-align: center;
background: url("https://raw.githubusercontent.com/mdn/learning-area/main/javascript/apis/fetching-data/can-store/icons/bean_can.png")
no-repeat 0% center,
url("https://raw.githubusercontent.com/mdn/learning-area/main/javascript/apis/fetching-data/can-store/icons/bean_can.png")
no-repeat 100% center;
background-size: 0.75em;
}
body {
border: var(--bw-2) solid var(--c-bd-1);
}
header,
aside,
main,
footer {
padding: var(--padding-md);
border: var(--bw-2) solid var(--c-bd-1);
}
[class*="l-with-sidebar"] {
align-items: stretch;
}
[class*="l-with-sidebar"] > aside {
flex-basis: 17rem;
}
main {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 13rem), 1fr));
align-content: start;
gap: var(--s-400);
}
footer {
font-size: var(--s-300);
}
/* Form */
input,
select {
border-color: var(--c-bd-1);
}
label,
button {
font-weight: 800;
}
form {
display: flex;
flex-wrap: wrap;
gap: var(--s-400);
}
form > * {
flex: 1 10rem;
}
form > .form-search {
flex-grow: 999;
}
form > button {
align-self: end;
}
form :is(input, select) {
inline-size: 100%;
}
/* Products */
section {
position: relative;
display: flex;
flex-direction: column;
border: var(--bw-3) solid currentColor;
border-radius: var(--border-radius);
}
section > h2 {
flex-grow: 1;
}
section h2 {
display: flex;
align-items: center;
justify-content: flex-end;
padding: var(--padding-xxs);
padding-block-end: var(--padding-xs);
padding-inline-start: 4rem;
font-size: var(--s-500);
line-height: 1;
text-align: end;
color: var(--c-bg-1);
background-color: var(--c-tx-1);
background-repeat: no-repeat;
background-size: 1em;
background-position: 0.5em center;
}
.meat h2 {
background-image: url("https://raw.githubusercontent.com/mdn/learning-area/main/javascript/apis/fetching-data/can-store/icons/meat.png");
}
.soup h2 {
background-image: url("https://raw.githubusercontent.com/mdn/learning-area/main/javascript/apis/fetching-data/can-store/icons/soup.png");
}
.vegetables h2 {
background-image: url("https://raw.githubusercontent.com/mdn/learning-area/main/javascript/apis/fetching-data/can-store/icons/vegetable.png");
}
section p {
position: absolute;
inset-inline-end: 2%;
inset-block-end: 2%;
}
.price {
display: inline-grid;
place-content: center;
inline-size: 3.5em;
block-size: 3.5em;
font-weight: 800;
line-height: 1;
text-align: center;
color: var(--c-tx-2);
background-color: var(--c-bg-2);
border: var(--bw-2) solid;
border-radius: 50%;
}
.sticky-footer {
display: flex;
flex-direction: column;
}
.sticky-footer > * {
flex-shrink: 0;
}
.sticky-footer__grow {
flex-grow: 1;
}
const productsURL =
"https://raw.githubusercontent.com/mdn/learning-area/main/javascript/apis/fetching-data/can-store/products.json";
// use fetch to retrieve it, and report any errors that occur in the fetch operation
// once the products have been successfully loaded and formatted as a JSON object
// using response.json(), run the initialize() function
fetch(productsURL).then(function (response) {
if (response.ok) {
response.json().then(function (json) {
initialize(json);
});
} else {
console.log(
"Network request for products.json failed with response " +
response.status +
": " +
response.statusText
);
}
});
// sets up the app logic, declares required variables, contains all the other functions
function initialize(products) {
// grab the UI elements that we need to manipulate
var category = document.querySelector("#category");
var searchTerm = document.querySelector("#searchTerm");
var searchBtn = document.querySelector("button");
var main = document.querySelector("main");
// keep a record of what the last category and search term entered were
var lastCategory = category.value;
// no search has been made yet
var lastSearch = "";
// these contain the results of filtering by category, and search term
// finalGroup will contain the products that need to be displayed after
// the searching has been done. Each will be an array containing objects.
// Each object will represent a product
var categoryGroup;
var finalGroup;
// To start with, set finalGroup to equal the entire products database
// then run updateDisplay(), so ALL products are displayed initially.
finalGroup = products;
updateDisplay();
// Set both to equal an empty array, in time for searches to be run
categoryGroup = [];
finalGroup = [];
// when the search button is clicked, invoke selectCategory() to start
// a search running to select the category of products we want to display
searchBtn.onclick = selectCategory;
function selectCategory(e) {
// Use preventDefault() to stop the form submitting — that would ruin
// the experience
e.preventDefault();
// Set these back to empty arrays, to clear out the previous search
categoryGroup = [];
finalGroup = [];
// if the category and search term are the same as they were the last time a
// search was run, the results will be the same, so there is no point running
// it again — just return out of the function
if (
category.value === lastCategory &&
searchTerm.value.trim() === lastSearch
) {
return;
} else {
// update the record of last category and search term
lastCategory = category.value;
lastSearch = searchTerm.value.trim();
// In this case we want to select all products, then filter them by the search
// term, so we just set categoryGroup to the entire JSON object, then run selectProducts()
if (category.value === "All") {
categoryGroup = products;
selectProducts();
// If a specific category is chosen, we need to filter out the products not in that
// category, then put the remaining products inside categoryGroup, before running
// selectProducts()
} else {
// the values in the <option> elements are uppercase, whereas the categories
// store in the JSON (under "type") are lowercase. We therefore need to convert
// to lower case before we do a comparison
var lowerCaseType = category.value.toLowerCase();
for (var i = 0; i < products.length; i++) {
// If a product's type property is the same as the chosen category, we want to
// dispay it, so we push it onto the categoryGroup array
if (products[i].type === lowerCaseType) {
categoryGroup.push(products[i]);
}
}
// Run selectProducts() after the filtering has been done
selectProducts();
}
}
}
// selectProducts() Takes the group of products selected by selectCategory(), and further
// filters them by the tnered search term (if one has bene entered)
function selectProducts() {
// If no search term has been entered, just make the finalGroup array equal to the categoryGroup
// array — we don't want to filter the products further — then run updateDisplay().
if (searchTerm.value.trim() === "") {
finalGroup = categoryGroup;
updateDisplay();
} else {
// Make sure the search term is converted to lower case before comparison. We've kept the
// product names all lower case to keep things simple
var lowerCaseSearchTerm = searchTerm.value.trim().toLowerCase();
// For each product in categoryGroup, see if the search term is contained inside the product name
// (if the indexOf() result doesn't return -1, it means it is) — if it is, then push the product
// onto the finalGroup array
for (var i = 0; i < categoryGroup.length; i++) {
if (categoryGroup[i].name.indexOf(lowerCaseSearchTerm) !== -1) {
finalGroup.push(categoryGroup[i]);
}
}
// run updateDisplay() after this second round of filtering has been done
updateDisplay();
}
}
// start the process of updating the display with the new set of products
function updateDisplay() {
// remove the previous contents of the <main> element
while (main.firstChild) {
main.removeChild(main.firstChild);
}
// if no products match the search term, display a "No results to display" message
if (finalGroup.length === 0) {
var para = document.createElement("p");
para.textContent = "No results to display!";
main.appendChild(para);
// for each product we want to display, pass its product object to fetchBlob()
} else {
for (var i = 0; i < finalGroup.length; i++) {
fetchBlob(finalGroup[i]);
}
}
}
// fetchBlob uses fetch to retrieve the image for that product, and then sends the
// resulting image display URL and product object on to showProduct() to finally
// display it
function fetchBlob(product) {
// construct the URL path to the image file from the product.image property
var url =
"https://raw.githubusercontent.com/mdn/learning-area/main/javascript/apis/fetching-data/can-store/images/" +
product.image;
// Use fetch to fetch the image, and convert the resulting response to a blob
// Again, if any errors occur we report them in the console.
fetch(url).then(function (response) {
if (response.ok) {
response.blob().then(function (blob) {
// Convert the blob to an object URL — this is basically an temporary internal URL
// that points to an object stored inside the browser
var objectURL = URL.createObjectURL(blob);
// invoke showProduct
showProduct(objectURL, product);
});
} else {
console.log(
'Network request for "' +
product.name +
'" image failed with response ' +
response.status +
": " +
response.statusText
);
}
});
}
// Display a product inside the <main> element
function showProduct(objectURL, product) {
// create <section>, <h2>, <p>, and <img> elements
var section = document.createElement("section");
var heading = document.createElement("h2");
var para = document.createElement("p");
para.classList.add("price");
var image = document.createElement("img");
// give the <section> a classname equal to the product "type" property so it will display the correct icon
section.setAttribute("class", product.type);
// Give the <h2> textContent equal to the product "name" property, but with the first character
// replaced with the uppercase version of the first character
heading.textContent = product.name.replace(
product.name.charAt(0),
product.name.charAt(0).toUpperCase()
);
// Give the <p> textContent equal to the product "price" property, with a $ sign in front
// toFixed(2) is used to fix the price at 2 decimal places, so for example 1.40 is displayed
// as 1.40, not 1.4.
para.textContent = "$" + product.price.toFixed(2);
// Set the src of the <img> element to the ObjectURL, and the alt to the product "name" property
image.src = objectURL;
image.alt = product.name;
// append the elements to the DOM as appropriate, to add the product to the UI
main.appendChild(section);
section.appendChild(heading);
section.appendChild(para);
section.appendChild(image);
}
}
Also see: Tab Triggers