Simple jQuery Click Not Working, though console log recognizes the function [closed]

Loading a jQuery dialogue in a plugin.

  1. Enqueue at Admin Enqueue Scripts

    function enqueue_settings_scripts_styles($page) {
        wp_enqueue_script (  'my-plugin', 'path/to/the.js', array( 'jquery-ui-dialog' ));
    }
    add_action('admin_enqueue_scripts', enqueue_settings_scripts_styles');
    
  2. The HTML

    <a style="cursor:pointer" class="cool-button">Click Me</a>
    
  3. Script (the.js)

    (function($) {
      console.log( "ready!" ); // this happens
      var detailsButton = $('a.cool-button');
      console.log(detailsButton.click);
      // this prints out to console:
      // function (a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}
    
    
      detailsButton.click(function(e) {
        alert('i happened'); // never happens
        e.preventDefault();
      });
    })(jQuery);
    

I have spent over an hour trying to troubleshoot this. What am I missing?

1 Answer
1

When enqueuing a script, you should state your script’s dependencies. In your case, it’s jQuery.

Enqueue your script in the following way:

wp_enqueue_script (  'my-plugin', 'path/to/the.js', array( 'jquery' ) );

You may also want to ensure that your script IS loaded in the footer, by setting the last argument to true:

wp_enqueue_script (  'my-plugin', 'path/to/the.js', array( 'jquery' ), null, true);

Where null would be the version number and true states that the script needs to be loaded in the footer.

Leave a Comment