0

I am trying to change the classes for the "View cart" button after adding an item to the cart. What I tried to do is to hook into the "woocommerce_ajax_added_to_cart" action and insert my Javascript as below but this Breaks the AJAX call. I honestly don't know if I am using the correct hook:

function set_button_classes() {

    echo "<script>document.getElementByClassName('added_to_cart wc-forward').classList.add('ct-cart-item', 'ct-offcanvas-trigger');</script>";

}
add_action( 'woocommerce_ajax_added_to_cart', 'set_button_classes', 10, 1 ); 

Any pointers would be really appreciated.

1
  • ˋadd_action( 'woocommerce_ajax_added_to_cart', 'set_button_classes', 10, 0 );` will be fairer.
    – FS-GSW
    Commented Dec 28, 2021 at 16:36

2 Answers 2

0

Going by your method I would suggest hooking into wp_footer as well, so that your script would be near the end of the body, that way it will be loaded after all DOM was loaded.

add_action('woocommerce_ajax_added_to_cart', 'set_button_classes');
function set_button_classes () {
    add_action('wp_footer', function () {
        echo "<script>document.getElementByClassName('added_to_cart wc-forward').classList.add('ct-cart-item', 'ct-offcanvas-trigger');</script>";
    });
}

You could also close the php tag and reopen it in the wp_footer anonymos function to make it easier to understand/see the scrip code

add_action('woocommerce_ajax_added_to_cart', 'set_button_classes');
function set_button_classes () {
    add_action('wp_footer', function () {
        ?>
        <script>
            document.getElementByClassName('added_to_cart wc-forward').classList.add('ct-cart-item', 'ct-offcanvas-trigger');
        </script>
        <?php
    });
}
0

Found an answer on here. It does work but I am having timing issues I think. They are unrelated to the question though so I will mark the below as the answer. Thanks all.

add_action( 'wp_footer', 'trigger_for_ajax_add_to_cart' );
function trigger_for_ajax_add_to_cart() {
    ?>
        <script type="text/javascript">
            (function($){
                $('body').on( 'added_to_cart', function(){
                    // Testing output on browser JS console
                    console.log('added_to_cart'); 
                    // Your code goes here
                });
            })(jQuery);
        </script>
    <?php
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.