Loading a jQuery dialogue in a plugin.
-
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');
-
The HTML
<a style="cursor:pointer" class="cool-button">Click Me</a>
-
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
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.