2

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

2

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.

5
  • I wish that was the answer. I am actually using jquery-ui-dialogue which also pulls in the other two dependencies (jquery and jquery-ui). I had just left them out for brevity as click itself itn't working. Also you can see that jQuery is enqueued because it prints out it's click function to the console, right?
    – MikeiLL
    Aug 2, 2017 at 7:06
  • 1
    This was bugging me too a few days back, until I realized I needed to set the jQuery as a dependency. By the way seeing jQuery being enqueued is not enough. If it's not the case, I'm afraid this question would be off-topic, since it's a jQuery question rather than WordPress. But if you haven't tried, it's worth trying array( 'jquery', 'jquery-ui-dialog' ).
    – Johansson
    Aug 2, 2017 at 7:08
  • I think when I set jquery-ui-dialogas a dependency, it also sets jquery as a dependency. It's possible this is just a jQuery issue. I'm simply not sure yet, because it is within WP that it's happening.
    – MikeiLL
    Aug 2, 2017 at 7:11
  • array( 'jquery', 'jquery-ui-dialog' ) doesn't seem to make a difference.
    – MikeiLL
    Aug 2, 2017 at 7:18
  • 1
    I think the issue is that I needed to set the final argument to wp_enqueue_script so that it enqueues in the footer.
    – MikeiLL
    Aug 2, 2017 at 7:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.