I couldn’t find any WP specific event to hook in to. What you can do is set up an observer with a callback to respond to DOM changes using MutationObserver
and check if the your featured image has been added in the callback.
There’s no support in IE < 11 though, which may be a deal breaker for you, or maybe not.
I’ve done minimal testing on this, but it works for me:
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
// Fires every time a mutation occurs...
// forEach all mutations
mutations.forEach(function(mutation) {
// Loop through added nodes
for (var i = 0; i < mutation.addedNodes.length; ++i) {
// any images added?
if ( mutation.addedNodes[i].getElementsByTagName('img').length > 0) {
alert('Featured Image Added');
// Your featured image now exists
console.log( $('#postimagediv img') );
// Do some AJAX...
}
}
});
});
// define what element should be observed (#postimagediv is the container for the featured image)
// and what types of mutations trigger the callback
var $element = $('#postimagediv');
var config = { subtree: true, childList: true, characterData: true };
observer.observe( $element[0], config );
There’s probably a better way to check for the featured image than just checking for an img
element. You may want to have a var to keep track of the featured image so you can easily check for it being removed too (or just check removedNodes
in the observer callback).
This won’t run on page load so you should check if a featured image exists there first.
Further reading on the Mutation Observers: