Search code examples
javascriptjquerywordpressfunctionready

How to access a function from one script in another script in JavaScript jQuery


In wordpress, i have two scripts enqueued in the functions.php one after another like this:

First enqueue jQuery:

function enqueue_scripts() {
wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'enqueue_scripts');

Then the scripts:

add_action('wp_enqueue_scripts', 'enqueue_my_scripts'); 
function enqueue_my_scripts() {
wp_enqueue_script(
    'script1',
    get_template_directory_uri() . '/assets/js/script1.js',
    array('jquery'), '1.0', true
);
wp_enqueue_script(
    'script2',
    get_template_directory_uri() . '/assets/js/script2.js',
    array('jquery'), '1.0', true
);
} 

The content of my script1.js:

 jQuery(document).ready(function($) {
   function myFunction1() {
   // do something
   }
 });

The content of my script2.js:

 jQuery(document).ready(function($) {

         myFunction1();

});

Error in console: Uncaught ReferenceError: myFunction1 is not defined in script2.js

I checked the Network tab, the scripts are loaded and are in the right order, no other errors.

I've tried a couple of things, like changing the jQuery of script1.js to plain Javascript and put it in global scope without the document ready function, nothing worked. Why is the function myFunction1 not accessible in my script2.js? How can i resolve the error?


Solution

  • Your function doesn't need to wait that the DOM is fully loaded, so don't use jQuery ready() event with your function, as it's not needed and don't allow your 2nd script to find the function.

    Update: You should add to your function, the $ shorthand as an argument, to avoid "Uncaught TypeError: $ is not a function" when using $ shorthand inside that function (see below: code example updated).

    The content of script1.js file:

    function myFunction1($) {
        const content = '<p style="color:red;border:solid 2px red;">Success: function called… <strong>Click me to remove me</strong></p>';
    
        console.log('success: function called');
    
        $(document.body).prepend('<div class="sprout">'+content+'</div>');
    
        $(document.body).on('click', '.sprout', function (){
            console.log('click: removed');
            $(this).remove();
        });
    };
    

    In your 2nd Script, we use the ready() event method, as it requires to wait that the DOM is fully loaded and safe to be manipulated.

    The content of script2.js file:

    jQuery(function($) {
        myFunction1($);
    });
    

    Note: jQuery(document).ready(function($){ and jQuery(function($){ are the same.

    See jQuery .ready() event documentation