Reputation: 1023
I am trying to create a JavaScript file that uses jQuery to create an on-click event for a button.
I can't however get it to work and I'm not even sure if the script is loading. I have searched for it in the page source but it is not there so that would suggest that it is not loading at all. I am new to plugins and jQuery but I followed a tutorial and copied the below code.
<?php
/*
Plugin Name: PansHousePlugin
Plugin URI: http://pans-house.com
Description: Adds OnClick and Scroll Functionality
Version: 1.0
Author: Paul Leppard
Author URI: http://pans-house.com
*/
add_action('wp_enqueue_scripts', 'load_js');
function load_js() {
wp_register_script('click_scroll', plugins_url( 'click_scroll.js', __FILE__), array( 'jQuery'), true );
wp_enqueue_script('click_scroll');
}
?>
and the click_scroll.js file which is in the same folder as the plugin.php file
(function($){
$(function(){
$("#gopricing").hide();
$(".showpricingbutton").on("click", function(){
$("#gopricing").toggle();
});
});
}(jQuery));
Like I said this is exactly as the tutorial says. The plugin is activated without any errors but the div with the id gopricing is not hidden and the button does not do anything on clicking it, so I am assuming the script has not been loaded.
Thanks
Upvotes: 0
Views: 73
Reputation: 19308
You're listing a dependency that doesn't exist.
jQuery
is the name of the library; the handle you need to refer to it with in order to load the library however is jquery
. You're also setting the version number to true when I believe you were instead trying to tell the JS to load in the footer.
Change this:
wp_register_script('click_scroll', plugins_url( 'click_scroll.js', __FILE__), array( 'jQuery'), true );
To this:
wp_register_script( 'click_scroll', plugins_url( 'click_scroll.js', __FILE__ ), array( 'jquery' ), false, true );
The next issue you have is with your JS. The final line needs an adjustment to the brackets and you should be waiting for the ready event:
(function( $ ) {
$( document ).ready(function() {
$( "#gopricing" ).hide();
$( ".showpricingbutton" ).on( "click", function() {
$( "#gopricing" ).toggle();
});
});
})( jQuery );
Further reading: https://developer.wordpress.org/reference/functions/wp_enqueue_script/
Upvotes: 1