How to capture the selection:toggle event fired by wp.media

I was able to cobble something together. I feel like there is a better approach to solving this, but that it might help to share my progress anyway.

The main trick came from this answer by @Vladimir Lukyanov.

My main concern with this solution is that the unselect event, "selection:unsingle", is triggered twice. I was unable to prevent this from happening.

The other concern is just that there is probably a cleaner way of accomplishing this. However, after lots of searching and experimenting, this is the closest I came to a solution.

add_action( 'admin_print_footer_scripts', 'wpse_media_library_selection_toggle' );
function wpse_media_library_selection_toggle() { ?>
<script type="text/javascript">
    ( function( $ ) {
        $( document ).ready( function() {

            // Ensure the wp.media object is set, otherwise we can't do anything.
            if ( wp.media ) {

                wp.media.featuredImage.frame().on('selection:toggle', function() {
                        console.log( 'image selected' );
                });

                // Ensure that the Modal is ready.
                wp.media.view.Modal.prototype.on( "ready", function() {
                    // console.log( "media modal ready" );

                    // Execute this code when a Modal is opened.
                    wp.media.view.Modal.prototype.on( "open", function() {
                        // console.log( "media modal open" );

                        // The sidebar boxes get deleted and recreated on each select - hack into this to do the same.
                        var selection = wp.media.frame.state().get( "selection" );
                        selection.on( "selection:single", function ( event ) {
                            console.log( "selection:single" );
                        } );

                        // Not sure why, but this fires twice...
                        selection.on( "selection:unsingle", function ( event ) {
                            console.log( "selection:unsingle" );
                        } );    

                    });

                    // Execute this code when a Modal is closed.
                    wp.media.view.Modal.prototype.on( "close", function() {
                         // console.log( "media modal close" );
                    });
                });
            }

        });
    })( jQuery );
</script><?php
}

Leave a Comment