Search code examples
jquerywordpressadvanced-custom-fieldswordpress-gutenberg

How to run jQuery code on WordPress admin?


How do you run a jQuery script when creating a new post. I was able to enqueue the script and can see the .js file in the editor but the code won't execute. I know there's a special way to run jquery code in the admin but can't find that way. The code is a simple script to change the background of a button that's using ACF when you click on it. I was able to get it to work on codepen - https://codepen.io/openbayou/pen/MWjOOZM

Here's the code:

<div class="acf-field acf-field-button-group acf-field-5fe2d3efcb5f8" data-name="box_photo_deets" data-type="button_group" data-key="field_5fe2d3efcb5f8" data-conditions="[[{&quot;field&quot;:&quot;field_5f8bec0f9f45d&quot;,&quot;operator&quot;:&quot;!=empty&quot;}]]">
   <div class="acf-label"></div>
   <div class="acf-input">
      <input type="hidden" name="acf-block_5fe163b63d274[field_5fe2d3efcb5f8]">
      <div class="acf-button-group"><label class="selected"><input type="radio" name="acf-block_5fe163b63d274[field_5fe2d3efcb5f8]" value="box_show_deets" checked="checked"> Show details</label></div></div>
</div>

Here's the script:

(function ($) {
$(window).on('my.custom.event', function () {
    $(".acf-field-5fe2d3efcb5f8 .acf-input .acf-button-group label").click(function(){
        $(".acf-field-5fe2d3efcb5f8 .acf-input .acf-button-group label.selected").css('background','black');
    });
});
})(jQuery);

jQuery(window).trigger('my.custom.event');

Solution

  • Let the DOM ready before the logic.

    (function($) {
        $(document).ready(function() {
    
           $(".acf-field-5fe2d3efcb5f8 .acf-input .acf-button-group label")
           .click(function() {
               $(".acf-field-5fe2d3efcb5f8 .acf-input .acf-button-group label.selected")
               .css('background','black');
           });
        });
    })(jQuery);