In the years since i posted my first answer, i have found a better way to do this that utilizes Magento's Require JS mixin utility. This is much more streamline and works better with long term site updates.
You can create a mixin in your require.js
config file:
app/design/frontend/{{vendor_name}}/theme/requirejs-config.js
let config = {
config: {
mixins: {
'Magento_Catalog/js/catalog-add-to-cart': {
'Magento_Catalog/js/catalog-add-to-cart-mixin': true
}
}
}
};
This will act as an injector to the original file. No file override, no coping code, no risk when you go and update Magento. You can read more on mixins here: https://alanstorm.com/the-curious-case-of-magento-2-mixins/
Create the mixin file and add this:
app/design/frontend/{{vendor_name}}/theme/Magento_Catalog/web/js/catalog-add-to-cart-mixin.js
define([
'jquery'
], function($) {
"use strict";
return function (widget) {
$.widget('mage.catalogAddToCart', widget, {
/**
* Handler for the form 'submit' event
*
* @param {Object} form
*/
submitForm: function (form) {
this.showCart();
this.ajaxSubmit(form);
},
/**
* Open minicart when Add To Cart has been clicked
*/
showCart: function() {
let self = this;
$('.block-minicart').dropdownDialog('open');
$(this.options.dropdownDialogSelector).addClass('minicart-loading');
$(this.options.minicartSelector).on('contentUpdated', function () {
$(self.options.dropdownDialogSelector).removeClass('minicart-loading');
});
}
});
return $.mage.catalogAddToCart;
}
});
Inside this file you have created an injector into the original file and the return that with your added code with return $.mage.catalogAddToCart;
. I found it is required that you include submitForm()
to get this working. Without it I found the add to cart button wouldn't enable on the product page. Inside that function call, you can place any custom call you like, in our case we are just calling showCart()
which opens the minicart for us when add to cart is clicked.