Product Cards in Vanilla JavaScript

Product Cards in Vanilla JavaScript
Project: Food Cards - Truncate Text
Author: Javier Eufracio
Edit Online: View on CodePen
License: MIT

This Vanilla JavaScript code snippet helps you to create product cards. The cards come with a thumbnail, product title, description, and product price. The card_content div contains the name of the product item (in an h2 tag with a class of card_title), the price (in a span tag with a class of orange), a description (in a div tag with a class of card_text), and a button with a class of card_btn that can be clicked to reveal more information about the item.

You can integrate these cards for your e-commerce store or portfolio items where your customer can interact with your products. Similarly, you can also use these cards for blog posts.

How to Create Product Cards in Vanilla JavaScript

First of all, load the Normalize CSS by adding the following CDN link into the head tag of your HTML document.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

Create the HTML structure for the product cards as follows. Update the card’s content according to your products.

<div class="main">
	<ul class="cards">
		<li class="cards_item">
			<div class="card">
				<div class="card_image"><img src="https://assets.codepen.io/652/photo-1468777675496-5782faaea55b.jpeg" alt="mixed vegetable salad in a mason jar. " /></div>
				<div class="card_content">
					<h2 class="card_title">Farmstand Salad <span class="orange">&#x2022; $9</span></h2>
					<div class="card_text">
						<p>
							Dig into the freshest veggies of the season! This salad-in-a-jar features a mixture of leafy greens and seasonal vegetables, fresh from the
							farmer's market.
						</p>
						<p>
							Served with your choice of dressing on the side: housemade ranch, cherry balsamic vinaigrette, creamy chipotle, avocado green goddess, or honey
							mustard. Add your choice of protein for $2 more.
						</p>
					</div>
					<button class="card_btn orange">See more +</button>
				</div>
			</div>
		</li>

		<li class="cards_item">
			<div class="card">
				<div class="card_image"><img src="https://assets.codepen.io/652/photo-1520174691701-bc555a3404ca.jpeg" alt="a Reuben sandwich on wax paper. " /></div>
				<div class="card_content">
					<h2 class="card_title">Ultimate Reuben <span class="orange">&#x2022; $18</span></h2>
					<div class="card_text">
						<p>
							All great meals take time, but this one takes it to the next level! More than 650 hours of fermenting, brining, aging, and curing goes into each
							and every one of our legendary Reuben sandwiches.
						</p>
						<p>
							Every element of this extraordinary sandwich is handcrafted in our kitchens, from the rye bread baked from our secret recipe to the cave-aged
							Swiss cheese, right down to the pickle. The only thing we didn't make on the premises is the toothpick ( but we're looking into how to do that).
						</p>
						<p>
							This unforgettable sandwich has all of the classic Reuben elements: corned beef, rye bread, creamy Russian dressing, sauerkraut, plus a sweet
							gherkin pickle. No substitions please!
						</p>
						<p>Add a side of french fries or sweet potato fries for $2 more, or our housemade pub chips for $1.</p>
					</div>
					<button class="card_btn orange">See more +</button>
				</div>
			</div>
		</li>
		<li class="cards_item">
			<div class="card">
				<div class="card_image">
					<img src="https://assets.codepen.io/652/photo-1544510808-91bcbee1df55.jpeg" alt="A side view of a plate of figs and berries. " />
				</div>
				<div class="card_content">
					<h2 class="card_title">Fig &amp; Berry Plate <span class="orange">&#x2022; $16</span></h2>
					<span class="note-sm">Seasonal.</span>
					<div class="card_text">
						<p>A succulent sextet of fresh figs join with a selection of bodacious seasonal berries in this refreshing, shareable dessert.</p>
						<p>Choose your drizzle: cherry-balsamic vinegar, local honey, or housemade chocolate sauce.</p>
					</div>
					<button class="card_btn orange">See more +</button>
				</div>
			</div>
		</li>
	</ul>
</div>

Now, style the product cards using the following CSS styles:

/* Mohave & Open Sans Fonts */
@import url("https://fonts.googleapis.com/css2?family=Mohave:wght@300;700&family=Open+Sans&display=swap");
/* Fonts & Colors */
:root {
  --title-font: "Mohave", sans-serif;
  --body-font: "Open Sans", sans-serif;
  --orange: hsl(0, 100%, 65%);
  --lighter-orange: hsl(0, 100%, 77%);
  --grey: hsl(197, 3%, 46%);
  --dark: hsl(0, 0%, 16%);
  --white: hsl(0, 0%, 100%);
}

/* General */
*,
*::before,
*::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

::selection {
  background-color: var(--lighter-orange);
  color: var(--white);
}

body {
  background-image: url("https://github.com/Javieer57/CPC-Card-Text/blob/main/assets/wood.jpg?raw=true");
  color: var(--dark);
  font-family: var(--body-font);
}

p {
  margin: 0;
}
p:not(:last-child) {
  margin-bottom: 14px;
}

ul {
  list-style: none;
}

img {
  width: 100%;
}

/* Layout */
.main {
  max-width: 1200px;
  margin: 0 auto;
}

/* Typography */
.card_title {
  font-family: var(--title-font);
  font-size: 28px;
  line-height: 24px;
  text-transform: uppercase;
}

.card_text p {
  font-family: var(--body-font);
  font-size: 14px;
  line-height: 24px;
}

/* Utilities */
.orange {
  color: var(--orange);
}

.note-sm {
  color: var(--grey);
  font-family: var(--title-font);
  font-size: 14px;
}

/* Components */
.cards {
  align-items: start;
  display: flex;
  flex-wrap: wrap;
  margin: 50px 0;
}
.cards_item {
  display: flex;
  padding: 1rem;
}

.card {
  background-color: var(--white);
  border-radius: 0.25rem;
  box-shadow: 0 20px 40px -14px rgba(0, 0, 0, 0.25);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.card_content {
  padding: 26px 16px 16px;
}
.card_title {
  margin-bottom: 5px;
}
.card_text {
  margin: 16px 0;
}
.card_btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 12px;
  text-transform: capitalize;
  font-family: var(--body-font);
  float: right;
}
.card_btn:hover {
  text-decoration: underline;
}

/* Media queries */
@media (min-width: 40rem) {
  .cards_item {
    width: 50%;
  }
}
@media (min-width: 56rem) {
  .cards_item {
    width: 33.3333%;
  }
}

Finally, add the following JavaScript function:

/**
 * Truncate a string
 * @param {string} text - text you want to be truncate
 * @param {number} letters - number of letters in the truncated text
 * @returns {string} - returns an truncated text within an <p> element to be insert as HTML
 */
function truncateText(text, letters = 135) {
	let truncatedText = text.slice(0, letters);
	let truncatedToHTML = `<p class="truncate">${truncatedText}...</p>`;

	return truncatedToHTML;
}

/* Select all card text containers */
let cards = document.getElementsByClassName("card_text");

/* Save texts within the cards as plain text */
let plainText = [];
for (let i = 0; i < cards.length; i++) {
	plainText[i] = cards[i].innerText;
}

/* Save the original card texts */
let htmlText = [];
for (let i = 0; i < cards.length; i++) {
	htmlText[i] = cards[i].innerHTML;
}

/* Add truncated text inside the cards */
for (let i = 0; i < cards.length; i++) {
	cards[i].innerHTML = truncateText(plainText[i]);
}

/* Add events to all buttons */
let btns = document.getElementsByClassName("card_btn");

for (let i = 0; i < cards.length; i++) {
	btns[i].addEventListener("click", function () {
		/* If the first child in the card text container has 'truncate' class... */
		if (cards[i].firstChild.className == "truncate") {
			/* Add their full text */
			cards[i].innerHTML = htmlText[i];
		} else {
			/* Add their truncated text */
			cards[i].innerHTML = truncateText(plainText[i]);
		}
	});
}

That’s all! hopefully, you have successfully integrated these product cards. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply