How to Change CSS Variable value in Theme Customizer Live Preview

Quick Note:

It looks like you may want to use a Color Control instead of excluding type and getting the default text control.

For example, this will turn your text input into a color picker…

$wp_customize->add_control(
    new WP_Customize_Color_Control(
        $wp_customize,
        'primary_color',
        [
            'label'   => __( 'Primary Color', 'mytheme' ),
            'section' => 'mytheme_color_options',
            'type' => 'color'
        ]
    )
);

You don’t give many details about your problem, what errors your getting or what your trying to achieve. Or why you are using a Custom Property Variable?

Anyway, I don’t think you can use jQuery to access the variable that way. Try this…

( function( $ ) {
    wp.customize(
        'primary_color',
        function ( value ) {
            value.bind(
                function ( to ) {
                    document.body.style.setProperty('--primary', to);
                }
            );
        }
    );
} )( jQuery );

Update:

jQuery only supports CSS custom properties in version 3.2.0 and later. There is no support for them in 2.x or earlier, so accessing them with .css() will not work in those versions.

Leave a Comment