Changing Customizer control choices via Javascript
-
I’m implementing a font selection choice in my theme, once the user selects the desired font, I need to run some code to present them with a list of the available font weights (Google Fonts). Not all fonts have all weights available, so I need this as a sanity check to avoid undesirable values.
The simplest route to do this seemed to be with Javascript firing an OnChange event, but after some trial and error, I found that I wasn’t able to get this to work. In my functions.php at the very bottom (after my customizer sections have been set up) I have this:
<script> document.getElementByID("_customize-input-body_font").onchange = function() {setSizesBody()}; function setSizesBody() { alert ("This is a warning message!"); var theFont = document.getElementByID("_customize-input-body_font"); var arrayOptions = []; document.getElementByID("_customize-input-body_font_weight").innerHTML = arrayOptions,join(); } </script>
Full disclosure, it’s been years since I’ve worked with Javascript, so I’m googling a bit more than usual on this. But from what I’m reading, the above code should have set up an onchange trigger for the body_font field, and when a new value there is updated, I should then have gotten a visible alert on my screen, and this never happens. The following code there should have just blanked out the available selections for the weight setting, I can finish that code easily enough once I can get this part to work.
My customizer controls are set up as follows, the sanitize function I have on the font choice just makes sure the font name entered is a valid Google font, that is working correctly.
$wp_customize->add_setting( 'body_font', array( 'default' => $the_fonts['body'], 'transport' => 'refresh', 'sanitize_callback' => 'throwback_sanitize_font_body', ) ); $wp_customize->add_control( 'body_font', array( 'label' => __( 'Google font for content', 'throwback' ), 'section' => 'font_family-settings', 'type' => 'text', 'input_attrs' => array( 'placeholder' => __( 'Enter any Google Font name', 'throwback' ), 'list' => 'throwback-fonts-list', ), ) ); $wp_customize->add_setting( 'body_font_weight', array( 'transport' => 'refresh', 'default' => 400, 'sanitize_callback' => 'throwback_sanitize_number_absint', ) ); $wp_customize->add_control( 'body_font_weight', array( 'type' => 'select', 'label' => __( 'Weight', 'throwback' ), 'section' => 'font_settings', 'choices' => $body_sizes, ) );
- The topic ‘Changing Customizer control choices via Javascript’ is closed to new replies.