admin管理员组

文章数量:1122832

This is the code.

jQuery(document).ready(function() {
    jQuery( '#menu-item-927' ).on( 'ubermenuopen', function(){
      jQuery('.site-content').addClass('blur');
    });
});

It works when I use it in the console but does not work when in a JS file.

Here are the things I have tried:

  1. Enqueued script with jQuery dependency wp_enqueue_script( 'script', get_stylesheet_directory_uri() . '/custom.js', array( 'jquery' ), '1.0.0', false ); and custom.js does show up in the source.
  2. Added jQuery(document).ready(function().

P.S: ubermenuopen is an events API from the UberMenu plugin.

This is the code.

jQuery(document).ready(function() {
    jQuery( '#menu-item-927' ).on( 'ubermenuopen', function(){
      jQuery('.site-content').addClass('blur');
    });
});

It works when I use it in the console but does not work when in a JS file.

Here are the things I have tried:

  1. Enqueued script with jQuery dependency wp_enqueue_script( 'script', get_stylesheet_directory_uri() . '/custom.js', array( 'jquery' ), '1.0.0', false ); and custom.js does show up in the source.
  2. Added jQuery(document).ready(function().

P.S: ubermenuopen is an events API from the UberMenu plugin.

Share Improve this question asked Mar 25, 2021 at 1:33 Stanley TanStanley Tan 1951 gold badge1 silver badge10 bronze badges 7
  • 3 "custom.js does show up in the source" - but is the file actually loaded? Try adding alert( 'custom.js' ) in the file and see if you get the alert. Also, there might be other dependencies that you must specify, e.g. ubermenu? – Sally CJ Commented Mar 25, 2021 at 2:39
  • @SallyCJ Yes, I added alert( 'Load me!' ); in the custom.js file and the alert did show up. – Stanley Tan Commented Mar 25, 2021 at 4:13
  • Which theme is active? child or main? – Bhautik Commented Mar 25, 2021 at 4:34
  • 1 @StanleyTan, as I said, try adding ubermenu as a dependency (array( 'jquery', 'ubermenu' )), but you'll need to identify the correct script handle like the 'script' in your wp_enqueue_script() code. You could also try enqueueing your script in the footer - set the fifth parameter to true. – Sally CJ Commented Mar 25, 2021 at 18:59
  • 1 @SallyCJ Adding the ubermenu dependency worked! Thank you! – Stanley Tan Commented Mar 31, 2021 at 4:26
 |  Show 2 more comments

1 Answer 1

Reset to default 0

I tested and works fine. but you can use the wp_footer hook and you can add your custom js. check below code. code will go to the active theme functions.php file.

function add_custom_scripts(){ ?>
<script type="text/javascript">
    (function($){
        $(document).ready(function() {
            $( '#menu-item-927' ).on( 'ubermenuopen', function(){
              $('.site-content').addClass('blur');
            });
        });
    })(jQuery);
</script>
<?php }
add_action( 'wp_footer', 'add_custom_scripts', 10, 1 );

本文标签: jQuery works in console but not when in a file