Execute javscript when theme customizer loads (autosave issue)
-
I have a theme that is having an issue when there are unsaved theme changes, then the user restores an autosave.
My theme has some jquery that watches for a font to be changed, then updates a second control with new font weights, and also updates a div label with the current font name. The problem is when the autosave is restored, my font selection shows the autosaved font name, but the weights section shows the previously published value still. My jquery doesn’t realize that the font name has been updated by the autosave.
I’m thinking that the best way to handle this is to trigger a javascript that will run as soon as the autosave is restored, but I can’t figure out a way to accomplish this.
What I’m trying now is the following: I’m already enquing a script successfully for other functions. I’ve created a new function inside that script as follows:
( function( wp, $ ) { function bob() { alert('bob'); } // Etc } )( wp, jQuery );
I’m enquing this script successfully using the following code, then inserting an inline script. This does insert inline successfully, but I get an error that bob is undefined.
function mytheme_enqueue() { global $theFontsList; wp_enqueue_style( 'mytheme-fonts', throwback_fonts_url(), array(), null ); wp_enqueue_script ( 'mytheme_font_js', get_template_directory_uri().'/inc/font.js', array('customize-controls'), false, true); wp_add_inline_script( 'mytheme_font_js', 'const theFont = ' . json_encode( $theFontsList ) .';', 'before' ); wp_add_inline_script( 'mytheme_font_js', 'bob();', 'after' ); }
My resulting HTML looks like this:
<script id='mytheme_font_js-js-before'> const theFont = // Removed for brevity </script> <script src='https://example.com/test/wp-content/themes/mytheme/inc/font.js?123&ver=6.1.1' id='mytheme_font_js-js'></script> <script id='mytheme_font_js-js-after'> bob(); </script>
- The topic ‘Execute javscript when theme customizer loads (autosave issue)’ is closed to new replies.