Create Add to Cart Button: HTML, CSS, JavaScript Tutorial

Faraz

By Faraz -

Learn how to create a seamless Add to Cart button using HTML, CSS, and JavaScript with our step-by-step tutorial.


Create Add to Cart Button HTML, CSS, JavaScript Tutorial.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

Adding an Add to Cart button is essential for any e-commerce website. It enables users to easily purchase products with just a click, enhancing the overall shopping experience. In this guide, we'll explore how to create and customize an Add to Cart button using HTML, CSS, and JavaScript. Whether you're a beginner or an experienced developer, this tutorial will provide you with the necessary steps to implement this crucial functionality on your website. Let's get started!

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our add to cart button.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Let's break down what each part does:

1. <!DOCTYPE html>: This declaration specifies the document type and version of HTML being used.

2. <html lang="en">: This tag indicates the beginning of the HTML document and specifies that the language used is English.

3. <head>: This section contains metadata about the document, such as the title, character encoding, viewport settings, and links to external resources like stylesheets and scripts.

  • <meta charset="UTF-8">: This meta tag specifies the character encoding of the document as UTF-8, which supports a wide range of characters from various languages.
  • <meta http-equiv="X-UA-Compatible" content="IE=edge">: This meta tag specifies the version of Internet Explorer to use for rendering the webpage. In this case, it's set to use the latest version available.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: This meta tag sets the viewport properties, ensuring the webpage is rendered properly on different devices and screen sizes.
  • <title>Add to Cart Button</title>: This sets the title of the webpage, which appears in the browser's title bar or tab.
  • <link href="https://f..." rel="stylesheet">: This links to external stylesheets from Google Fonts, importing the PT Sans and Ubuntu fonts with a font-weight of 500.
  • <link rel="stylesheet" href="styles.css">: This links to an external CSS file named "styles.css" that contains additional styles for the webpage.

4. <body>: This section contains the visible content of the webpage.

5. <div class="container">: This <div> element serves as a container for the button.

6. <button class="add-to-cart-button">: This <button> element creates the "Add to Cart" button and assigns it a class for styling purposes.

7. Inside the button, there are several <svg> elements and <span> elements:

  • <svg> elements: These are scalable vector graphics used for icons like a box, a cart, and a tick.
  • <span> elements: These are used to display text like "Add to cart" and "Added to cart".

8. <script src="script.js"></script>: This includes an external JavaScript file named "script.js", which contains additional functionality for the webpage, such as handling button clicks.

This is the basic structure of our add-to-cart button using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the button is in place, the next step is to add styling to the button using CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our button.

Let's break down what each part does:

1. body { margin: 0; }: This sets the margin of the entire body of the webpage to zero, ensuring there's no extra space around the edges.

2. .container: This class styles a container element that holds the "Add to Cart" button. It uses flexbox properties to vertically and horizontally align its content in the center of the viewport.

3. .add-to-cart-button: This class styles the "Add to Cart" button itself. It sets various properties including background color, border, border-radius (rounded corners), box-shadow for a subtle shadow effect, color, font family, padding, text transformation to uppercase, and transition for smooth animations. It also specifies a minimum width, hides overflow, and removes the outline.

4 .add-to-cart-button:active: This pseudo-class styles the button when it's in an active state (clicked). It changes the box-shadow and applies a downward transformation to simulate a pressed effect.

5. .add-to-cart-button:hover: This pseudo-class styles the button when hovered over with the mouse, changing the cursor to a pointer and applying a slight upward transformation to give a raised effect.

6. .add-to-cart-button:hover, .add-to-cart-button:focus: This targets both hover and focus states of the button and applies similar styles as the :hover state.

7. .add-to-cart-button.added: This class styles the button when it's been clicked and the item has been added to the cart. It changes the background color and box-shadow to indicate the success of the action.

8. .add-to-cart-button.added .add-to-cart and .add-to-cart-button.added .added-to-cart: These styles are applied to the "Add to cart" and "Added to cart" text spans respectively when the button has been clicked and the item has been added to the cart. It hides the "Add to cart" text and shows the "Added to cart" text.

9. .add-to-cart-button.added .cart-icon, .add-to-cart-button.added .box-1, .add-to-cart-button.added .box-2, .add-to-cart-button.added .tick: These styles control the animation of different elements within the button when the item has been added to the cart, such as the cart icon, boxes, and tick animation.

10. .add-to-cart, .added-to-cart: These classes style the "Add to cart" and "Added to cart" text spans respectively, setting their margin and display properties.

11. .add-to-cart-box and .box-1, .box-2: These classes style the box elements used as decorative elements within the button, positioning them absolutely and setting their size and transition properties.

12. .cart-icon and .tick: These classes style the cart icon and the tick mark within the button, positioning them absolutely and setting their size, background color, border-radius, and transformation properties.

13. @keyframes grow and @keyframes drop: These are keyframe animations used to create the growing and dropping effects for the tick mark and cart icon when the item is added to the cart. They define different stages of transformation during the animation. These animations are defined for both regular CSS and vendor-prefixed (webkit) versions for compatibility with different browsers.

This will give our add-to-cart button an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

body{margin:0}
.container {
  align-items: center;
  display: flex;
  justify-content: center;
  height: 100vh;
}

.add-to-cart-button {
  background: #e6a247;
  border: none;
  border-radius: 4px;
  box-shadow: 0 3px 13px -2px rgba(0, 0, 0, 0.15);
  color: #ffffff;
  display: flex;
  font-family: "Ubuntu", sans-serif;
  justify-content: space-around;
  min-width: 195px;
  overflow: hidden;
  outline: none;
  padding: 0.8rem;
  position: relative;
  text-transform: uppercase;
  transition: 0.4s ease;
  width: auto;
}
.add-to-cart-button:active {
  box-shadow: 0 0 0 0.2rem rgba(252, 186, 3, 0.45);
  transform: translateY(4px);
}
.add-to-cart-button:hover {
  cursor: pointer;
}
.add-to-cart-button:hover, .add-to-cart-button:focus {
  box-shadow: 0 0 0 0.2rem rgba(252, 186, 3, 0.45);
  transform: translateY(-1px);
}
.add-to-cart-button.added {
  background: #2fbf30;
  box-shadow: 0 0 0 0.2rem rgba(11, 252, 3, 0.45);
}
.add-to-cart-button.added .add-to-cart {
  display: none;
}
.add-to-cart-button.added .added-to-cart {
  display: block;
}
.add-to-cart-button.added .cart-icon {
  animation: drop 0.3s forwards;
  -webkit-animation: drop 0.3s forwards;
  -webkit-animation-delay: 0.18s;
          animation-delay: 0.18s;
}
.add-to-cart-button.added .box-1,
.add-to-cart-button.added .box-2 {
  top: 18px;
}
.add-to-cart-button.added .tick {
  animation: grow 0.6s forwards;
  -webkit-animation: grow 0.6s forwards;
  -webkit-animation-delay: 0.7s;
          animation-delay: 0.7s;
}

.add-to-cart,
.added-to-cart {
  margin-left: 36px;
}

.added-to-cart {
  display: none;
  position: relative;
}

.add-to-cart-box {
  height: 5px;
  position: absolute;
  top: 0;
  width: 5px;
}

.box-1,
.box-2 {
  transition: 0.4s ease;
  top: -8px;
}

.box-1 {
  left: 23px;
  transform: rotate(45deg);
}

.box-2 {
  left: 32px;
  transform: rotate(63deg);
}

.cart-icon {
  left: 15px;
  position: absolute;
  top: 8px;
}

.tick {
  background: #146230;
  border-radius: 50%;
  position: absolute;
  left: 28px;
  transform: scale(0);
  top: 5px;
  z-index: 2;
}

@-webkit-keyframes grow {
  0% {
    -webkit-transform: scale(0);
  }
  50% {
    -webkit-transform: scale(1.2);
  }
  100% {
    -webkit-transform: scale(1);
  }
}
@keyframes grow {
  0% {
    transform: scale(0);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}
@-webkit-keyframes drop {
  0% {
    -webkit-transform: translateY(0px);
  }
  100% {
    -webkit-transform: translateY(1px);
  }
}
@keyframes drop {
  0% {
    transform: translateY(0px);
  }
  100% {
    transform: translateY(1px);
  }
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript.

Let's break down what each part does:

1. addToCartButton = document.querySelectorAll(".add-to-cart-button");: This line selects all elements with the class "add-to-cart-button" and assigns them to the variable addToCartButton.

2. document.querySelectorAll('.add-to-cart-button'). forEach(function(addToCartButton) { ... });: This code iterates over each element with the class "add-to-cart-button" and adds an event listener to it.

3. addToCartButton.addEventListener('click', function() { ... });: This line adds a click event listener to each "Add to Cart" button. When clicked, the function inside the event listener is executed.

4. addToCartButton.classList.add('added');: When the button is clicked, this line adds the class "added" to the button's class list. This triggers a change in the button's appearance to indicate that the item has been added to the cart.

5. setTimeout(function(){ ... }, 2000);: This line sets a timeout function that removes the "added" class from the button after a delay of 2000 milliseconds (2 seconds). This simulates a temporary visual indication that the item has been added to the cart.

6. addToCartButton.classList.remove('added');: After the specified timeout, this line removes the "added" class from the button, reverting its appearance to its original state.

Create a JavaScript file with the name script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

addToCartButton = document.querySelectorAll(".add-to-cart-button");

document.querySelectorAll('.add-to-cart-button').forEach(function(addToCartButton) {
    addToCartButton.addEventListener('click', function() {
        addToCartButton.classList.add('added');
        setTimeout(function(){
            addToCartButton.classList.remove('added');
        }, 2000);
    });
});

Final Output:

Create Add to Cart Button HTML, CSS, JavaScript Tutorial.gif

Conclusion:

Congratulations on completing this tutorial on creating an Add to Cart button using HTML, CSS, and JavaScript! By following the steps outlined in this guide, you've learned how to structure the HTML, style it with CSS, and add functionality with JavaScript to create a seamless user experience for your e-commerce website.

Keep exploring and experimenting with customization options to tailor the Add to Cart button to your website's design and branding. With dedication and practice, you'll master the art of creating dynamic and engaging user interfaces that drive success for your online store. Happy coding!

Code by: Kieran Brown

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post