Score:-2

I cannot call a function in another JavaScript file

bi flag

I have two JavaScript files on my custom theme. One file has functions that need to be used on the other file. What I have below doesn't work. This is the error I get.

Uncaught ReferenceError: test is not defined.

jQuery will be used on both files.

file1.js

/**
 * @file
 * UI behaviors
 */

(function ($, Drupal) {

 'use strict';

  $(document).ready(function () {
    function test(){
     console.log('hello'):
    }
  });

})(jQuery, Drupal);

file2.js

/**
 * @file
 * UI behaviors
 */

(function ($, Drupal) {

  'use strict';

  $(document).ready(function () {
     test();
  });

})(jQuery, Drupal);

customtheme.libraries.yml

scripts:
  js:
    js/file1.js: {}
    js/file2.js: {}

customtheme.info.yml

libraries:
 - 'customtheme/scripts'
Score:1
de flag

This is because test() is wrapped in an anonymous function, making it not available outside of that function.

I would add it to the Drupal object:

File 1:

(function($, Drupal) {
  Drupal.myFunction = function() {
    // Do something.
  }
}(jQuery, Drupal));

File 2:

(function($, Drupal) {
  Drupal.myFunction();
});

Also, as a side note, $(document).ready() is not used in Drupal. In Drupal Drupal.behaviors is used instead: https://www.drupal.org/docs/drupal-apis/javascript-api/javascript-api-overview

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.