Execute jQuery with custom event listener after successfully add an item to the cart

This is my first post, so please be gentle. I'm already successfully executing some jQuery codes in my woocommerce cart-page after updating the item quantity (Ajax) with the following code:

$( document.body ).on( 'updated_cart_totals', function(){
    //re-do your jquery
});

I also need a similar function to execute a jQuery code after adding a cross selling item (with click on the ajax_add_to_cart_button) in the cart-page. So far i checked the cart.js file to find a custom event to handle this - but i was not able to find a solution. Any idea how to execute a jQuery code after successully adding a cross selling item to the cart in the cart-page?

Topic woocommerce-offtopic functions events jquery Wordpress

Category Web


From a cursory overview, the cross-sells are added via the same ajax add to cart script as regular shop loop archive products and I don't see a way to distinguish between when it's a cross-sell and when it's not. You could run a script conditionally only on the cart page, and then listen to the added_to_cart trigger, which might then only be happening for cross sells (assuming you don't have other ajax add to cart buttons on the cart page)

Or it appears that the add to cart button is passed as a variable to the added_to_cart trigger. You may be able to do some DOM manipulation there to see if it was part of the cross sells div. Totally wild guess:

$( document.body ).on( 'added_to_cart', function( event, fragments, cart_hash, $button ){
    if( $button.closest( 'div.cross-sells' ) ) {
        // was a cross-sell added to the cart
    }
});

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.