Magento 2.2: Add To Cart Pop-up Modal Guide

by Marco 44 views

Implementing a "Product Added to Cart" Pop-up Modal in Magento 2.2

Hey guys, ever noticed how a simple "Add to Cart" button can kick off a whole chain of events behind the scenes? Today, we're diving into a cool little tweak for your Magento 2.2 store: creating a pop-up modal that confirms when a product has been successfully added to the cart. This is a super handy feature because it gives immediate feedback to your customers, making the whole shopping experience feel smoother and more user-friendly. If you're like me, you know how important it is to keep your customers informed every step of the way! We'll go through the steps to make it happen and get you up and running. Let's break this down step by step, making sure we cover all the important stuff. I have seen a lot of times that customers did not notice the change, and this is a great way to ensure that they know the product has been added to the cart!

So, we're aiming to create a pop-up modal. This is the cool little window that will appear right after someone clicks that "Add to Cart" button, displaying a message like, "Product added to cart!" This seemingly small addition can seriously boost user experience. It eliminates any confusion or doubt the customer might have about whether their action was successful. This is also really great because you can customize the popup to fit the theme of your website. Let's get started!

Step 1: Setting Up the Module (if you haven't already)

First things first, you'll need a module. If you already have one, great! If not, don't worry, creating a module is like setting up the foundation of your house. Create the directory structure of the module. For example, let's say your vendor name is "YourCompanyName" and the module name is "AddToCartPopup". The directory structure should look something like this:

app/code/YourCompanyName/AddToCartPopup/
├── etc/
│   └── module.xml
└── registration.php

Inside app/code/YourCompanyName/AddToCartPopup/etc/module.xml, you define the module's metadata:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="YourCompanyName_AddToCartPopup" setup_version="1.0.0">
    </module>
</config>

And in app/code/YourCompanyName/AddToCartPopup/registration.php, register your module:

<?php
use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(
    ComponentRegistrar::MODULE,
    'YourCompanyName_AddToCartPopup',
    __DIR__
);

After creating the module files, you'll need to enable the module. Go to your Magento root directory and run the following commands in your terminal:

php bin/magento module:enable YourCompanyName_AddToCartPopup
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento cache:flush

Step 2: Creating the Layout File

Next, we're going to tell Magento where to put our code. We'll do this by creating a layout file. Inside your module, create the file app/code/YourCompanyName/AddToCartPopup/view/frontend/layout/catalog_product_view.xml. This file will be responsible for injecting our JavaScript code into the product detail page. You can name this file according to your preference to have a different functionality. This layout file will be crucial. The core of this part is to integrate your js code. Now, we will inject the required javascript and css for the modal pop-up

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="YourCompanyName_AddToCartPopup::css/add-to-cart-popup.css"/>
    </head>
    <body>
        <referenceContainer name="before.body.end">
            <block class="Magento\Framework\View\Element\Template" name="addtocart.popup" template="YourCompanyName_AddToCartPopup::addtocartpopup.phtml"/>
            <script src="YourCompanyName_AddToCartPopup::js/add-to-cart-popup.js"/>
        </referenceContainer>
    </body>
</page>

In this layout file:

  • We add a CSS file to style the pop-up. Create a CSS file at app/code/YourCompanyName/AddToCartPopup/view/frontend/web/css/add-to-cart-popup.css.
  • We add the block that will hold the HTML for the modal. Create a template file at app/code/YourCompanyName/AddToCartPopup/view/frontend/templates/addtocartpopup.phtml.
  • We include a JavaScript file to handle the modal's behavior. Create a JavaScript file at app/code/YourCompanyName/AddToCartPopup/view/frontend/web/js/add-to-cart-popup.js.

Step 3: Building the Modal's HTML

Now, let's set up the HTML structure for our pop-up modal. Open the file app/code/YourCompanyName/AddToCartPopup/view/frontend/templates/addtocartpopup.phtml and add the HTML for the modal. This is where you define what the user actually sees when the modal appears. This gives you full control of the look and feel of the message

<div id="add-to-cart-modal" style="display: none;">
    <div class="modal-content">
        <span class="close-button">&times;</span>
        <p>Product added to cart!</p>
    </div>
</div>

In this HTML:

  • We have a main div with the id add-to-cart-modal. This is our modal container, initially hidden.
  • Inside, we have the content of the modal, including a close button and the message "Product added to cart!". Feel free to customize the message and add any other elements you want.
  • You can also add a link to the cart here, to encourage the user to go to the cart page.

Step 4: Styling the Modal with CSS

Let's make sure our pop-up modal looks good. Open app/code/YourCompanyName/AddToCartPopup/view/frontend/web/css/add-to-cart-popup.css and add the styles for the modal. This CSS code is to style the modal

#add-to-cart-modal {
    display: none;
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0,0,0,0.4);
}

.modal-content {
    background-color: #fefefe;
    margin: 15% auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
    position: relative;
}

.close-button {
    position: absolute;
    top: 0px;
    right: 10px;
    font-size: 28px;
    font-weight: bold;
    color: #aaa;
}

.close-button:hover,
.close-button:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}

This CSS will:

  • Hide the modal by default using display: none;.
  • Position the modal in the center of the screen.
  • Style the modal content, including a close button. You can also add some animations to it

Step 5: Writing the JavaScript to Control the Modal

Finally, the brains of the operation – the JavaScript code. This is where we make everything interactive. Open the file app/code/YourCompanyName/AddToCartPopup/view/frontend/web/js/add-to-cart-popup.js and add the following JavaScript code:

require([ 'jquery' ], function($) {
    $(document).ready(function() {
        var modal = $('#add-to-cart-modal');
        var closeButton = $('.close-button');

        $(document).ajaxComplete(function(event, xhr, settings) {
            if (settings.url.includes('/checkout/cart/add')) {
                modal.css('display', 'block');
                setTimeout(function() {
                    modal.css('display', 'none');
                }, 3000);
            }
        });

        closeButton.click(function() {
            modal.css('display', 'none');
        });
    });
});

Let's break down the JavaScript code:

  • require([ 'jquery' ], function($) { ... });: This line loads the jQuery library, which is a JavaScript library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. In this case, we need it to manipulate elements and listen for events.
  • $(document).ready(function() { ... });: This ensures that the code runs after the HTML document has been fully loaded.
  • var modal = $('#add-to-cart-modal');: This line selects the modal element using its ID. We will need to use this to show and hide the modal
  • var closeButton = $('.close-button');: This line selects the close button element using its class. We will need to use this to hide the modal when the close button is clicked
  • $(document).ajaxComplete(function(event, xhr, settings) { ... });: This is the heart of our functionality. It listens for AJAX requests that are completed.
    • if (settings.url.includes('/checkout/cart/add')) { ... }: We check if the URL of the AJAX request includes "/checkout/cart/add". This is how we can identify the "Add to Cart" action. When you are implementing, this might be different depending on your configuration. It might be related to a certain product ID or category.
    • modal.css('display', 'block');: If the condition is met, the modal is shown by setting its display style to "block".
    • setTimeout(function() { modal.css('display', 'none'); }, 3000);: We use setTimeout to automatically hide the modal after 3 seconds (3000 milliseconds). You can customize this duration.
  • closeButton.click(function() { modal.css('display', 'none'); });: This handles the click event on the close button, hiding the modal when clicked.

Step 6: Clearing the Cache and Testing

After implementing all the files, it's essential to clear your Magento cache. Run the following commands in your terminal:

php bin/magento cache:clean
php bin/magento cache:flush

Now, go to a product page on your frontend and click the "Add to Cart" button. You should see the pop-up modal appear with the message "Product added to cart!" after the product is successfully added. If the modal doesn't show up, double-check your code for any typos or errors, and ensure that the module is enabled, deployed, and the cache is cleared. Make sure to check your browser's console for any errors that may have occurred.

Conclusion

And there you have it! You've successfully added a pop-up modal to your Magento 2.2 store, confirming to your customers that their products have been added to their carts. This not only enhances the user experience but also contributes to a more professional and trustworthy online store. Remember to test the functionality thoroughly and customize the message and appearance to match your brand's style. Enjoy, and happy coding!