0

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');
Gregory Schultz
  • 864
  • 7
  • 24
  • I don't understand why you are using this custom event? `my.custom.event`. I guess you want to change the background color on click event! – jogesh_pi Dec 26 '20 at 06:33
  • Do you see an error in the console? You might find this useful in debugging or understanding what is happening. https://stackoverflow.com/a/5706909/3825777 – react_or_angluar Dec 26 '20 at 07:20

1 Answers1

1

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);
jogesh_pi
  • 9,762
  • 4
  • 37
  • 65