try use mixins,
Create a module and add files as below:
app/code/Vendor/Module/view/frontend/requirejs-config.js
var config = {
config: {
mixins: {
'Magento_Catalog/js/catalog-add-to-cart': {
'Advintage_CaseBuy/js/catalog-add-to-cart-mixin': true
}
}
}
};
app/code/Vendor/Module/view/frontend/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) {
//add new functionality
console.log('my code works.');
var addToCartButton, self = this;
if (form.has('input[type="file"]').length && form.find('input[type="file"]').val() !== '') {
self.element.off('submit');
// disable 'Add to Cart' button
addToCartButton = $(form).find(this.options.addToCartButtonSelector);
addToCartButton.prop('disabled', true);
addToCartButton.addClass(this.options.addToCartButtonDisabledClass);
form.submit();
} else {
self.ajaxSubmit(form);
}
}
});
return $.mage.catalogAddToCart;
}
});
We should use the javascript init method for adding the javascript to our page.
Javascript init method helps you to solve few problems.
They provide a standard mechanism to discourage directly embedding javascript into a page.
They provide a way to invoke a standalone RequireJS module (defined with define) as a program.
They provide a way to pass that program a server-side generated JSON object.
They provide a way to tell that program which (if any) DOM nodes it should operate on.
You can get more info here https://alanstorm.com/magento_2_javascript_init_scripts/
Now let's use this in your case.
Navigate to
Magento Admin > Content > CMS Pages > Homepage
Add following code in the content of homepage.
<script type="text/x-magento-init">
{
"*": {
"Vendor_Module/js/homepage": {}
}
}
</script>
Now create a homepage.js file
app/code/Vendor/Module/view/frontend/web/js/homepage.js
Add following code in the file
define([
'jquery'
], function (jQuery) {
'use strict';
return function (config) {
alert(jQuery('body').attr('class'));
// add your jQuery script here
}
});
Run command php bin/magento setup:static-content:deploy
Best Answer
The reason that this way using the alias
does not work is because in templates/product/view/addtocart.phtml
Magento uses a validation widget to help with product validation which also plugs the add to cart form's submit handler.While, following the dev docs instructions one might use the Alias to try and extend the widget, Magento invokes the widget internally.
To make it work correctly so the validations aren't lost, follow the steps below:
addtocart.phtml should have
{ "#product_addtocart_form": { "js/custom-validate-product": {} } }
create a new file js/custom-validate-product like this:
mage.catalogAddToCartWidget