Preserve Javascript Through Customizer Preview Navigation

In the Customizer you can add some javascript and put your control transport to refresh so that whenever the user changes a setting it automatically gets reflected onto the website preview panel:

// Body Background Color
wp.customize( 'body_bgr_color', function( control ) {
    control.bind( function( value ) {
        $( 'body' ).css( 'background-color', hex2rgba( value, 1 ) );
    } );
} );

I’m enqueueing my script using the customize_preview_init hook.

The issue happens whenever the user users the main navigation to go to the next page – the javascript changes are lost but preserved on the Controls Pane. How can I preserve or rerun the javascript whenever the user navigates to a new preview page?

1 Answer
1

Since I’m saving everything on hard save ( button click ) I was trying to avoid updating all the options via ajax. What the below does is as the preview pane is setting up the JS binding, I trigger a “change” which will reapply the controls value to the element. I’m certainly open to better options but this worked in my case:

jQuery( document ).ready( function( $ ) {

    // Body Background Color
    wp.customize( 'body_bgr_color', function( control ) {
        control.bind( function( value ) {
            $( 'body' ).css( 'background-color', hex2rgba( value ) );
        } );
        $( control ).trigger( 'change' );
    } );
} );

Leave a Comment