How do I run custom JS when a file is selected?
-
Hi. I’m replacing a metabox I built using core WP’s API with one built with CMB2. The goal of the box is to allow the user to select an image from the media library, and optionally customize the caption of the image for the current post. When an image is selected, I grab the caption from the selected image and stuff it into a WYSIWYG (TinyMCE) editor, where the user is free to edit it.
in my custom metabox I have a button labelled Add image. When the button is clicked, the code below is executed (only the relevant bits are shown).
If I use CMB2’s file field to select an image from the media library, what Javascript event should I hook on to in order to detect that an image was selected and grab its caption?
file_frame = wp.media.frames.file_frame = wp.media({
title: jQuery( this ).data( 'uploader-title' ),
button: {
text: jQuery( this ).data( 'uploader-button-text' ),
},
multiple: false
});file_frame.on( 'select', function() {
// multiple is false so we only get one image from the uploader
attachment = file_frame.state().get('selection').first().toJSON();
tinyMCE.get('caption-editor').setContent(attachment.caption);
- The topic ‘How do I run custom JS when a file is selected?’ is closed to new replies.