Trigger JS when featured image upload window is opened in admin

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

Leave a Comment