In default Magento2, when you add products to cart then total no. of item counts in Minicart will be updated with AJAX. But that minicart sidebar will not open to see the items contains in the cart currently.
In this post we wiil check how to auto open minicart sidebar after successfully added items into cart.
Let's start by creating custom module.
You can find complete module on Github at Magelearn_MinicartOpen
Create folder inside app/code/Magelearn/MinicartOpen
Add registration.php file in it:
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Magelearn_MinicartOpen', __DIR__ );
Add composer.json file in it:
{ "name": "magelearn/minicart-open", "description": "Open minicart after adding products to cart Magento 2", "type": "magento2-module", "license": "proprietary", "authors": [ { "name": "vijay rami", "email": "vijaymrami@gmail.com" } ], "minimum-stability": "dev", "require": {}, "autoload": { "files": [ "registration.php" ], "psr-4": { "Magelearn\\MinicartOpen\\": "" } } }
Add etc/module.xml file in it:
<?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="Magelearn_MinicartOpen" setup_version="1.0.0"></module> </config>
here first we will add our layout file. From that we call our custom phtml file and add custom JS to achieve this functionality.
Create default.xml file inside view/frontend/layout folder.
<?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"> <body> <referenceContainer name="content"> <block class="Magento\Framework\View\Element\Template" name="minicart.autoopen" template="Magelearn_MinicartOpen::minicart_open.phtml"/> </referenceContainer> </body> </page>
Now add minicart_open.phtml file inside view/frontend/templates/ folder.
<script type="text/x-magento-init"> { "[data-block='minicart']" : { "Magelearn_MinicartOpen/js/view/minicartopen" : {} } } </script>
From here we will call our JS component file.
Create view/frontend/web/js/view/minicartopen.js file.
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"); }); }); } });
We will also add requirejs-config.js file to define dependancy of Jquery for this JS file.
Add view/frontend/requirejs-config.js file.
var config = { map: { '*': { minicart_open: 'Magelearn_MinicartOpen/js/view/minicartopen' } }, shim: { minicart_open: { deps: [ 'jquery' ] } } };
0 Comments On "How to Auto Open Minicart After Item is added into cart Magento2"