1

I have started to build a Woocommerce site, created a variable product with 2 product attributes for variations. The first product attribute is "color" and the second is "size". I would like to add .background-black CSS class to my #primary Id when only the "color" product attribute has been changed and not "size". I grabbed the attribute ID through the URL that is displayed in the cart once the variation is selected: attribute_pa_color = black.

What I would like to know is if there is a way I could do this using jQuery with woocommerce I just don't know how to do it properly. I appreciate the help.

$(document).ready(function() {
    if ("attribute_pa_color = black") {
        $("#primary").toggleClass("background-black");
    }
});

closed as off-topic by bueltge, Jacob Peattie, rudtek, Mayeenul Islam, cjbj May 28 at 20:07

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

0

You can use the following to add/remove a customized class to #primary selector based on the selected product attribute "Color":

<script type="text/javascript">
jQuery(function($){
    var p = '#primary',
        c = $(p).prop('class'),
        s = 'select[name="attribute_pa_color"]';

    // On start
    if( $(s).val() !== '' ) {
        $(p).prop('class', 'background-'+$(s).val());
    }

    // On select (blur live event)
    $(s).blur( function() {
        var b = $(this).val() !== '' ? c+' background-'+$(this).val() : c;
        $(p).prop('class',b);
    });
});
</script>

Tested and works


You could also add directly a color-background CSS style instead to #primary selector, like:

<script type="text/javascript">
jQuery(function($){
    var p = '#primary',
        b = 'background-color',
        s = 'select[name="attribute_pa_color"]';

    // On start
    if( $(s).val() !== '' ) {
        $(p).css(b, $(s).val());
    }

    // On select (blur live event)
    $(s).blur( function() {
        if( $(this).val() !== '' )
            $(p).css(b, $(this).val());
        else
            $(p).removeProp('style');
    });
});
</script>

Tested and works too.

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