Bind event on Media gallery elements WordPress

(function ($) {
    "use strict";

    $(function () {

        var button = $('.upload-image');


        button.click(function (e) {

            e.preventDefault();

            // If the media frame already exists, reopen it.
            if (file_frame) {
                file_frame.open();
                return;
            }

            var btn = $(this),
                media = wp.media;


            // Create the media frame.
            var file_frame = media.frames.file_frame = media({
                title: jQuery(this).data('uploader_title'),
                button: {
                    text: jQuery(this).data('uploader_button_text')
                },
                library: {
                    type: 'image'
                },
                multiple: false
            });


            // Finally, open the modal
            file_frame.open();

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

            selection.on( 'selection:unsingle', function ( event ) {
                console.log('selection:unsingle');
            } );

        });

    });
}(jQuery));

NOTICE: “selection:unsingle” event will fire up twice

Leave a Comment