Executing Javascript When a Widget is Added in the Backend

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>

Leave a Comment