0

In the Theme Customizer preview I am using Modernizr to include certain classes that change the page styles. If I understand it correctly, changing the device type to tablet or mobile only changes the window size but doesn't trigger any callback or page reload.

Right now, the only way I can think of is adding a resize listener in my preview script and see which device do the new window dimensions match.

I would like to know if there is a built-in filter or way to trigger a callback in the preview window so I can include the correct class for each device view.

1 Answer 1

1

Yes, the way to accomplish this would be to send messages from the Customizer controls pane window to the Customizer preview window when the wp.customize.previewedDevice value changes.

So you can enqueue a script at the customize_controls_enqueue_scripts action with customize-controls as its script dependency that does:

(function ( api ) {
    api.bind( 'ready', function() {
        function sendPreviewedDevice() {
            api.previewer.send( 'previewed-device', api.previewedDevice.get() );
        }

        // Send the initial previewed device when preview is ready.
        api.previewer.bind( 'ready', sendPreviewedDevice );

        // Send the previewed device whenever it changes.
        api.previewedDevice.bind( sendPreviewedDevice );
    });
}) ( wp.customize );

That handles sending the message from the controls to the preview. Then you need a separate script in the preview to listen for the messages from the pane. Enqueue a separate script in wp_enqueue_scripts if is_customize_preview() such as the following:

(function ( api, $ ) {
    api.bind( 'preview-ready', function() {
        var previousPreviewedDevice = null;

        // Listen for a previewed-device message.
        api.preview.bind( 'previewed-device', function( previewedDevice ) {
            var body = $( document.body );
            if ( previousPreviewedDevice ) {
                body.removeClass( previousPreviewedDevice );
            }
            body.addClass( previewedDevice );
            previousPreviewedDevice = previewedDevice;
        });
    });
}) ( wp.customize, jQuery );

The result is that the device being previewed will appear as a class on the preview window's body element, for example tablet.

I've pushed this up into a standalone plugin in a Gist: https://gist.github.com/westonruter/b2fdf9347c8441ba9933569b15e2faa7

For more information, see also our Customizer Responsive Server-Side Components Device Preview plugin and its corresponding writeup: Previewing Themes with Adaptive Designs in the Customizer. This is probably closer to what you may be wanting since it seems you're not implementing a purely responsive theme.

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.