Wordpress - Executing Javascript When a Widget is Added in the Backend

As @aaron-holbrook commented a cleaner approach will be to do:

jQuery(document).on('widget-updated widget-added', function(){
    // your code to run
});

In many cases you will also want to run the JS when the page loads as well as when the widgets are updated. You may do so like this.

function handle_widget_loading(){
   // your code to run
}
jQuery(document).ready( handle_widget_loading );
jQuery(document).on('widget-updated widget-added', handle_widget_loading );

Just pasting here for reference as answers are much easier to find that comments


Great News,

I've fixed it.

Apologies for missing your gist in my initial comment and giving you an answer that you had already implemented. That'll teach me to answer on my phone while on a train!

Your use of ajaxstop is correct. Hell the JS for the most part is working correctly, you could see the css styles being initialized and the changes in the DOM.

The issue lies in fact with your selector.

This is because widget content isn't loaded in via ajax, in fact it clones it from the left hand column where it's hidden and then fires an ajax call to save the widget's position in the right hand column. This explains why ajaxstop works a treat, even thought content is cloned. However, because there is a hidden version of the widget in the left hand column, your JS is instantiating on that. As such when you drag it to the right hand column, you are getting a mangled clone of the hidden widget.

Thus you need to select the one in the left side. Below is the corrected code:

<script>
jQuery( document ).ready( function( $ ) {
    function runSelect() {
        var found = $( '#widgets-right select.testselectize' );
        found.each( function( index, value ) {

            $( value ).selectize();
                .removeClass( 'testselectize' )
                .addClass( 'run-' + window.counter );

            console.log( $val );
            window.counter++;
        } );
    }

    window.counter = 1;

    runSelect();

    $( document ).ajaxStop( function() {
        runSelect();
    } );
} );
</script>