3

I'm trying to hook up some JS so that when the featured image upload box is opened and an image selected I can use Vibrant.js to analyse the colours of the selected image. The hurdle I've encountered is that I can't find any particular event to bind my function to. I've looked at various tutorials regarding the wp.media() object, but they all seem to involve replacing the upload box completely. Is there no straightforward way of detecting when the featured image upload window is open and the selected thumbnail preview image is loaded?

2 Answers 2

7

After some digging I discovered that wp.media.featuredImage.frame() was what I was looking for:

wp.media.featuredImage.frame().on('open',function() {
    // Clever JS here
});

I then discovered that the select event fires once you've clicked on the 'Set featured image' button, not when you've clicked on thumbnail, which was what I was after. So I bound my events to the modal window itself once it was opened:

wp.media.featuredImage.frame().on('open', function() {
    // Get the actual modal
    var modal = $(wp.media.featuredImage.frame().modal.el);
    // Do stuff when clicking on a thumbnail in the modal
    modal.on('click', '.attachment', function() {
        // Stuff and thangs
    })
    // Trigger the click event on any thumbnails selected previously
    .find('attachment.selected').trigger('click');
});

The end result was that once the featured image modal was opened, it would fetch an uncropped version of the selected featured image via WP-JSON, extract the a palette of colours via Vibrant.js, and then add these as a colour picker to the modal. This let's you specify a particular colour - taken from the image - that then gets used by the theme as an overlay for that particular image. A picture explains this better:

Colour extraction in the featured image uploader

If anyone is interested I'll get round to writing this up in more detail in a blog post

1
  • 1
    Great stuff! For those who might want to hook into the 'select' event, here's the basic code: wp.media.featuredImage.frame().on('select', function() { /* do something */ }); Would be very interested in seeing your blog post! Commented Feb 17, 2016 at 22:54
2

You can also do the following (it will also fire on the regular media modal):

jQuery(document).ready(function($){
    if (wp.media) {
        wp.media.view.Modal.prototype.on('open', function() {
            console.log('media modal open');
        });
    }
});

btw, I got this snippet from Dekode

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.