Skip to content

Commit

Permalink
Merge pull request #438 from woocommerce/fix/add-to-cart-handler
Browse files Browse the repository at this point in the history
  • Loading branch information
tomalec committed Jun 18, 2024
2 parents 3d69739 + dd9211f commit 94b1245
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions assets/js/src/integrations/classic.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export function classicTracking(
} );

// Handle runtime cart events.
const oldAddedToCart = document.body.onadded_to_cart;
/**
* Track the custom add to cart event dispatched by WooCommerce Core
*
Expand All @@ -48,7 +49,15 @@ export function classicTracking(
* @param {string} cartHash - A string representing the hash of the cart after the update.
* @param {HTMLElement[]} button - An array of HTML elements representing the add to cart button.
*/
document.body.onadded_to_cart = ( e, fragments, cartHash, button ) => {
document.body.onadded_to_cart = function (
e,
fragments,
cartHash,
button
) {
if ( typeof oldAddedToCart === 'function' ) {
oldAddedToCart.apply( this, arguments );
}
// Get product ID from data attribute (archive pages) or value (single product pages).
const productID = parseInt(
button[ 0 ].dataset.product_id || button[ 0 ].value
Expand Down Expand Up @@ -99,20 +108,20 @@ export function classicTracking(
// Attach event listeners on initial page load and when the cart div is updated
removeFromCartListener();
const oldOnupdatedWcDiv = document.body.onupdated_wc_div;
document.body.onupdated_wc_div = ( ...args ) => {
document.body.onupdated_wc_div = function () {
if ( typeof oldOnupdatedWcDiv === 'function' ) {
oldOnupdatedWcDiv( ...args );
oldOnupdatedWcDiv.apply( this, arguments );
}
removeFromCartListener();
};

// Trigger the handler when an item is removed from the mini-cart and WooCommerce dispatches the `removed_from_cart` event.
const oldOnRemovedFromCart = document.body.onremoved_from_cart;
document.body.onremoved_from_cart = ( ...args ) => {
document.body.onremoved_from_cart = function () {
if ( typeof oldOnRemovedFromCart === 'function' ) {
oldOnRemovedFromCart( ...args );
oldOnRemovedFromCart.apply( this, arguments );
}
removeFromCartHandler( { target: args[ 3 ][ 0 ] } );
removeFromCartHandler( { target: arguments[ 3 ][ 0 ] } );
};

// Handle product selection events.
Expand Down

0 comments on commit 94b1245

Please sign in to comment.