Magento – Pop up minicart when I add a product to the cart magento 2

cartmagento2popup

I'm using magento 2.0.7, and what I'm trying to do is to popup the cart(the top right cart ajax minicart) when I add a product to it, Basically trigger it. I have tried to add the "showcart" class to my add to cart button classes, but if I do so, the button just opens the cart, and doesn't add the product anymore..

Best Answer

This is my first answer on this site. I've been struggling trying to make this work for the past two days and I was finally able to make it work, so I though it would be nice to share it.

First of all you need to create a module:

  • registration.php
  • etc/module.xml
  • view/frontend/layout/default.xml
  • view/frontend/templates/minicart_open.phtml
  • view/frontend/web/js/view/minicart_open.js

Step 1. You need to add a template to the site. The way to do that is by using the default.xml

<referenceContainer name="content">
  <block class="Magento\Framework\View\Element\Template" name="minicart.autoopen" template="Company_ModuleName::minicart_open.phtml"/>
</referenceContainer>

Step 2. Then inside minicart_open.phtml we need to call our js file (component) by attaching it to the parent div of the minicart. In this case, [data-block='minicart']. See this link for more details.

<script type="text/x-magento-init">
{
     "[data-block='minicart']" : {
        "Company_ModuleName/js/view/minicart_open" : {}
     }
}
</script>

Step 3. And finally, inside minicart_open.js, the magic code:

define(["jquery/ui","jquery"], function(Component, $){
    return function(config, element){
        var minicart = $(element);
        minicart.on('contentLoading', function () {
            minicart.on('contentUpdated', function () {
                minicart.find('[data-role="dropdownDialog"]').dropdownDialog("open");
            });
        });
    }
});

Basically this code extends the functionality of the file vendor/magento/module-checkout/view/frontend/web/js/view/minicart.js, and it says that once the AJAX call is completed (contentUpdated), the minicart should be opened.

And that's it, a simple task with a lot of theory behind. Hope it helps.

Related Topic