Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

Trigger JS in custom meta box if a featured image is loaded/exists

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:

  • https://www.w3.org/TR/dom/#mutation-observers

  • https://davidwalsh.name/mutationobserver-api

  • http://ryanmorr.com/using-mutation-observers-to-watch-for-element-availability/

  • https://stackoverflow.com/a/11546242/1990216

Related Posts:

  1. Add “upload media” button in meta box field
  2. post formats – how to switch meta boxes when changing format?
  3. How to add multiple featured image in meta box in post editor?
  4. Repeatable custom meta fields
  5. Dynamic Custom Fields
  6. How to create a button click counter meta box?
  7. delete post meta by AJAX
  8. How to disable drag-and-drop upload function in Media Library?
  9. Run javascript upon successfully set featured image
  10. Use AJAX to fetch Current Post Thumbnail for WordPress when Uploaded throughMedia Uploader Frontend
  11. delete post meta data in array WordPress
  12. Why does my media selection script write to ONLY the first input field?
  13. Collect custom post in a calendar
  14. WordPress AJAX load post metadata in modal
  15. Second featured image only shows in metabox preview after saving a post in the wordpress editor
  16. Dashboard – get status and position of metaboxes and pass them to ajax method
  17. window.send_to_editor throws unterminated string literal error when adding image with multi line description
  18. Audio Player for MP3 Files for WordPress
  19. splitting the URL using jQuery
  20. How select multiple document as like media gallery
  21. Rebuild the entire WordPress uploads folder
  22. Uppload image from another source wp.media
  23. Media Gallery Upload photo incorrect way like glitch
  24. Create a new post using rest api and save featured image using an external image url
  25. Status 400 for AJAX POST Request with admin-ajax.php
  26. Finding a media attachment post ID from a URL
  27. Javascript / Ajax Error After Migrating To New Domain Name
  28. AJAX Load more on CPT returning random posts
  29. A better way to add a meta box to custom post types
  30. wp_get_attachment_image_src() returns wrong url
  31. Ajax random number always the same
  32. Scripts not appending to element in AJAX call – why?
  33. Image upload via FormData API and AJAX is not working ($_FILES always empty)
  34. Create Media via REST API from Android Application
  35. Need Help Fixing My Iframes [closed]
  36. See List View – or Image titles- of Media Library when “Add Media” button is used
  37. Plugin – Combine Meta Box Input Fields into single saveble record
  38. How to hide some specific attachments using post meta from media library
  39. adding images column to admin edit columns not working for SVG
  40. How to upload media to a specific folder without a plugin in WordPress?
  41. How to extend an existing (Gutenberg) block
  42. JS innerhtml changing style when using AJAX
  43. Load MediaPlayerElement after Infinity Scroll loads more posts
  44. Overriding of the template for the Attachment “thumbnails” in the Media Grid isn’t working
  45. Multiple media uploader buttons target only one input on the same page
  46. It is possible to add custom media size in admin media edit?
  47. Set featured image using javascript in post editor
  48. wp.template() returns tags in Ajax response
  49. How to get Metabox custom field to show checked if value is updated using post meta query?
  50. Custom icons in media library
  51. Overwrite media matching post title using WP CLI’s media import command
  52. Limit number of images to upload in wp.media function
  53. Save Search System
  54. dynamic dependent select dropdown
  55. Refresh Markercluster after ajax call
  56. Importing Media IDs but not related attachment
  57. Moving media between blogs changes the URL subdirectory [closed]
  58. How to send Ajax request from my plugin in admin dashboard?
  59. Meta value does not save for scheduled posts
  60. Metabox not show in categories custom post type cmb2
  61. WooCommerce Ajax Cart Update Stopped Working
  62. Adding inline JavaScript encoding issue
  63. Link to resized media file
  64. Making an ajax request from a different domain
  65. Allow Editor Role to Edit Media
  66. Error: Warning: strpos() in media.php
  67. Bulk image importing from folders
  68. WordPress + JavaScipt + AJAX + MySQL: insert query for form
  69. Custom controller for video that is added from editor
  70. How to Dynamically Load Content Into Body of Bootstrap Modal Window?
  71. Password Protecting Media
  72. How to add a do_action on refreshing of WP customizer?
  73. Performance optimization of tree like structure
  74. How do I query posts by a sub value with the API?
  75. How to get media source of text editor in WordPress
  76. WordPress media file link with fancybox
  77. How to search using ajax for exact phrase or words in an input field?
  78. Creating subfolders in the media library
  79. WordPress media upload automatic refresh
  80. How to pass Select value from Javascript to PHP to generate select option on change
  81. Show preview of post changes on page
  82. how to upload file to media library using link [closed]
  83. How to open a Media Uploader dialog with a particular image is selected
  84. Can I Change the Media Upload Location for each user?
  85. How to update Comment post meta through an Ajax call
  86. Button inside Custom Meta Box triggering the Update Button
  87. Radio buttons live refresh in the customizer
  88. Why is my Custom Meta Box Field Inputs NOT saving?
  89. Update attachment metadata fails
  90. Allow downloading unusual file types
  91. Set spesific size of featured images
  92. Setting value of session with Ajax not working
  93. AJAX success response is not working but it’s saving my changes
  94. Is it possible to change filenames in media library after upload?
  95. Show Custom Post Type meta boxes only on Page Edit
  96. Gravity Forms closes my popup on Validation Error [closed]
  97. How to load wp_editor via AJAX
  98. How do I pass the id of my widget to javascript in the form function?
  99. AJAX not Working with php as supposed
  100. Upload featured image from front end using media-upload.php
Categories media Tags ajax, javascript, media, metabox, post-meta, post-thumbnails
Customizer options
hide something in single page if current author has only one post

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress