Support » Developing with WordPress » customizer control deactivation using JavaScrip API

  • Resolved tbaikamine

    (@tbaikamine)


    I have 2 customizer controls, the first is a radio type.
    I enqueued my script using “customize_controls_enqueue_scripts” hook
    I want the second control to appear/disappear based on the first control’s value.
    my javascript is:

    wp.customize.bind("ready", function () {
      var customize = this;
      customize("setting_name", function (setting) {
        setting.bind('change',function (value) {
          if(value=='desired_value'){
            wp.customize.control('second_control').activate()
        }
          else{
            wp.customize.control('second_control').deactivate()
        }
        });
      });
    });

    this works ! hoever couple of seconds letter the preview window refreshes and the second control just gets reactivated on its own.
    in absence of Javascript APIs documentation, is there someone who can explain this behavior to me or how to fix the issue ? thanks

Viewing 1 replies (of 1 total)
  • Thread Starter tbaikamine

    (@tbaikamine)

    sharing what I discovered with the community:
    when you visit the customizer page for the first time you need to distinguish between the “controls pane” ready and the “previewer” ready
    parts of the “controls pane” still get updates AFTER the “previewer” fully loads
    (when the previewer is not fully loaded you can notice the tab title showing: Loading…)
    so to resolve the issue, I enqueued a previewer script to send a custom event when it’s fully loaded to the “controls pane” script.
    the previewer script:

    (function ($) {
      $(document).ready(function () {
        // sends a preview-ready custom event with no data
        wp.customize.preview.send("preview-ready", null);
      });
    })(jQuery);

    enqueued this way:

    add_action('customize_preview_init',function(){
     
     wp_enqueue_script('preview_script',get_stylesheet_directory_uri().'preview_script.js',array('customize-preview','jquery'),false,true);
    });

    the controls pane script:

    (function ($) {
      $(document).ready(function () {
        wp.customize.previewer.bind("preview-ready", function () {
          // your logic here
        });
      });
    })(jQuery);

    enqueued this way:

    add_action('customize_controls_enqueue_scripts',function(){
     
     wp_enqueue_script('controls_script',get_stylesheet_directory_uri().'control_script.js',array('customize-controls','jquery'),false,true);
    });

    hope this helps 🙂

Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.