0

i am trying to dynamically change css of the mini-cart-widget contents with a random pick of predefined shop-colors. I do not know how to catch the moment when the mini-cart-widget is displayed on the front end. I tried:

//this snippet is in my standard.js document and loaded in the footer after jquery.min.js
var $match = $(document).find('.widget_shopping_cart').find('.mini_cart_item a');

if($match.length){
    console.log("widget_shopping_cart");
  }else{
    console.log("not available");
  }

It does not work. Then i tried:

//this snippet is in my standard.js document and loaded in the footer after jquery.min.js
$(document.body).on( 'added_to_cart', function() {
        console.log('product add to cart');
   });

As recommended in other places, i also tried the following:

// i added priority 40 to load the snippet after the jquery library
add_action( 'wp_footer', 'trigger_for_ajax_add_to_cart',40 );
function trigger_for_ajax_add_to_cart() {
    ?>
    <script type="text/javascript">
        (function($){
            $(document.body).on( 'added_to_cart', function(){
                // Testing output on browser JS console
                console.log('added_to_cart'); 
                // Your code goes here
            });
        })(jQuery);
    </script>
<?php
}

But this has no effect either. It is more or less the same as the previous attempt.

Is there a way to catch the moment when the mini-cart-widget content appears? How can i alter the css, for instance like this:

$('.mini_cart_item a.remove').css({
  'background-color': lightColor //variable for shop colors
});

Additional info: i have ajax-cart-button option active

timholz
  • 327
  • 1
  • 3
  • 14

1 Answers1

1

I found a solution using mutation observer. This function finds the element, that has been added dynamically, and then can be styled:

function onElementInserted(containerSelector, elementSelector, callback) {

var onMutationsObserved = function(mutations) {
    mutations.forEach(function(mutation) {
        if (mutation.addedNodes.length) {
            var elements = $(mutation.addedNodes).find(elementSelector);
            for (var i = 0, len = elements.length; i < len; i++) {
                callback(elements[i]);
            }
        }
    });
};

var target = $(containerSelector)[0];
var config = { childList: true, subtree: true };
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(onMutationsObserved);    
observer.observe(target, config);

}

onElementInserted('body', '.remove', function(element) {
//console.log(element);
$('.remove').css('background-color', randCol);
//catch the next sibling, which is <a>product name</a>
$('.remove').next().css('color', randCol);
});

thanks original source

Maybe there is a more elegant solution, a more woocommerce-like solution based on those magical javascript events, but the code shown above performs well so far...

timholz
  • 327
  • 1
  • 3
  • 14