Trigger JS when featured image upload window is opened in admin

The question:

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?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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

Method 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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment