0

I want to implement custom jQuery in one of the wordpress templates;

I added these lines to functions.php:

function my_custom_script() {
wp_enqueue_script('extra js', get_stylesheet_directory_uri() . '/js/extra.js');
}
add_action('wp_enqueue_scripts', 'my_custom_script');

Then I wanted to see if it works, so I simply added this to my extra.js file:

alert "Hello folks!";

And yup, alert appearing on the screen. Superb!

But if I want to add custom jQuery, let's say I got dic with id="firstBox":

$('#firstBox').click(function() {
    $('#firstBox').hide();
})

And nothing happens at all.

How to properly use jQuery in files like these?

mdmb
  • 4,833
  • 7
  • 42
  • 90
  • 1
    I found the answer here: http://stackoverflow.com/questions/12343714/typeerror-is-not-a-function-when-calling-jquery-function – mdmb Jan 12 '16 at 22:12

2 Answers2

0

Making sure jQuery is loaded properly

Firstly, ensure that jQuery is being properly loaded at all. Let's deregister the jquery packaged and load from the CDN to ensure we have everything we need.

function my_jquery_enqueue() {
    wp_deregister_script('jquery');
    wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
    wp_enqueue_script('jquery');
}
add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11);

Now, enqueue your script with jquery as a dependency.

function my_extra_enqueue() {
    wp_enqueue_script( 'extra_js', get_stylesheet_directory_uri() . '/js/extra.js', array('jquery') );
}
add_action("wp_enqueue_scripts", "my_extra_enqueue");

No Conflicts

If you're still having issues at that point and seeing errors in your console like $ is not a function than you'll need to write your script with a .noConflict() variable. Sample script may be like:

$j = jQuery.noConflict();

$j('#firstBox').click(function() {
    $j('#firstBox').hide();
})

There are quite a few ways to go about setting up .noConflict() so do some reading to pick what works best for you. READ: https://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_Wrappers

0

try to replace $ with jQuery

jQuery('#firstBox').click(function() {
    jQuery('#firstBox').hide();
})
Prakash Rao
  • 2,368
  • 1
  • 9
  • 12