Home > Software design >  Global JS function Not Available Wordpress - jQuery
Global JS function Not Available Wordpress - jQuery

Time:09-26

My global function is not available because "$ is not a function".

But I do have jquery as a dependency to my own js file:

wp_enqueue_script('common-js', get_stylesheet_directory_uri() . '/js/common.js', array('jquery'), CHILD_THEME_ASTRA_CHILD_VERSION, true);

enter image description here

Why I cannot use jQuery outside of document ready?

CodePudding user response:

try out the below code might help you in achieving the result.

jQuery(function($){
    
     function closeOverlay(){
        // Logic Here
     }
     function openOverlay(){
       // Logic Here 
     }

});

CodePudding user response:

This will create an anonymous function that will be called immediately ( Immediately Invoked Function Expression or IIFE ) with the $ param and the supplied value for the $ is jQuery. This way, you make sure that all the code inside this can use $ without polluting the global space

(function ($) {
    function whatever(){
        $('.selector').slideUp();
    }

    $(document).ready(function(){
       // some code here
    });
})(jQuery);
  • Related