• I’m working with JQuery and I have a bit of code that is watching for any changes to several fields, if a change is seen, then I need to set a Customizer control to a new value. But I’m not seeing a way to watch for changes to multiple controls. Here’s a sample of my code:

    
        wp.customize.control( 'page_bg_color', function( control ) {
            control.setting.bind( function( to ) {
                wp.customize('color_theme').set('custom');
            } );
        } );
        wp.customize.control( 'header_bg_color', function( control ) {
            control.setting.bind( function( to ) {
                wp.customize('color_theme').set('custom');
            } );
        } );

    With the above, changes to either of these two colors will update my ‘color_theme’ select to read ‘custom’, indicating the user has strayed from the preset options. My problem is that I have over a dozen colors, which would require a dozen or so similar functions to the above.

    I tried to see if I could pass in an array of color controls, but this did nothing at all (no errors) so I assumed such a thing wasn’t supported.

    wp.customize.control( ['page_bg_color', 'header_bg_color'],  function( control ) {
Viewing 2 replies - 1 through 2 (of 2 total)
  • You can wrap the code in a function and then call it for each control, instead of having to write out separate functions for each control. You can also use a loop to dynamically generate the function calls based on an array of control names. Here’s an example:

    var colorControls = ['page_bg_color', 'header_bg_color'];
    
    function updateColorTheme(controlName) {
      wp.customize.control( controlName, function( control ) {
        control.setting.bind( function( to ) {
          wp.customize('color_theme').set('custom');
        });
      });
    }
    
    for (var i = 0; i < colorControls.length; i++) {
      updateColorTheme(colorControls[i]);
    }
    Thread Starter jimwright2

    (@jimwright2)

    Appreciate the tip, I’ll test this out next chance I get. It should definitely clean things up and make updating easier.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Watch multiple controls for a change’ is closed to new replies.