Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

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.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

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.

+ add another resource

Packages

Add Packages

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.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <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>
              
            
!

CSS

              
                @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;
}

              
            
!

JS

              
                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);
	}
}

              
            
!
999px

Console