1

In my HTML I was loading JQuery, but I am not loading it when converting HTML into the Wordpress. because I think WP automatically loads it.

However there is a custom.js sitting in the js folder, and I am trying to load it like this →

if ( ! function_exists( 'puck_scripts' ) ) {
function puck_scripts() {

// Register the script like this for a theme:
    wp_register_script( 'custom-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '1.1', true );
    wp_enqueue_script( 'custom-js' );       
}

    add_action('wp_enqueue_scripts','puck_scripts');
    }

May be JQuery is not loading so custom.js doesn't work Should I load JQuery separately in theme functions.php? But I think I read somewhere that WP load JQuery. Or what I suspect is that JQuery is not loading before the custom.js. Maybe I have to declare something through some function that I do not know how to do.

Its been an hour, and I could not recognize what is wrong.

2

Your issue is that you are trying to use the normal jQuery shortcut ($) which doesn't work by default as the WordPress version of jQuery is in compatibility mode. You need to wrap the code in your custom.js file in an anonymous function to map jQuery to $ as shown below:

(function($) {

    //Your code here

})( jQuery );

or alternatively, replace all instances of '$' with 'jQuery'.

  • I am new to the development world. Please elaborate and elucidate. currently written like this: $(".class-name").on('click',function (e) {code here }); what should I do in such case? – The WP Intermediate Jul 10 '17 at 11:11
  • 1
    See edit with your code included inside the anonymous function. – Erbilacx Jul 10 '17 at 11:15
  • please delete the code that u have copy pasted from that site as it may be some copyright violations. I have understood Now. Please delete that code I will accept your answer. – The WP Intermediate Jul 10 '17 at 11:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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