Is it possible to trigger some JavaScript when Media Popup is opened?

You can use several event handlers.

frame.on('open',function() {
    // Do something
});

frame.on('close',function() {
    // Do something
});

frame.on('select',function() {
    // Do something
});

Where frame is a reference to wp.media()

frame = wp.media();

frame.on('select',function() {
    // Do something
});

Full example

Script en-queued with jQuery and media editor as dependencies.

function media_script_enqueue() {
   wp_enqueue_script( 'media-script', get_template_directory_uri() . '/js/media-script.js', array( 'jquery', 'media-editor' ), '', true );
}
add_action( 'wp_enqueue_scripts', 'media_script_enqueue' ); // Front-end
add_action( 'admin_enqueue_scripts', 'media_script_enqueue' ); // Back-end

Script contains:

;( function( $ ) {
    var frame = wp.media({
         multiple: true
    });

    $(".media").on("click", function(e) {
        frame.open();

        e.preventDefault();
    });

    frame.on('open', function() {
        console.log("Open");
    });

    frame.on('close', function() {
        console.log("Close");
    });

    frame.on('select', function() {
        console.log("Select");

        var selection = frame.state().get('selection');

        selection.each(function(attachment) {
            console.log(attachment.id);
        });
    });
} )( jQuery );

Window triggered by a button with a classname of media

<button class="media">Media</button>

Media javascript dependencies enqueued via function.

<?php wp_enqueue_media(array('post' => get_the_ID())); ?>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)