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.
/**
* @file
* UI behaviors
*/
(function ($, Drupal) {
'use strict';
$(document).ready(function () {
function test(){
console.log('hello'):
}
});
})(jQuery, Drupal);
/**
* @file
* UI behaviors
*/
(function ($, Drupal) {
'use strict';
$(document).ready(function () {
test();
});
})(jQuery, Drupal);
scripts:
js:
js/file1.js: {}
js/file2.js: {}
libraries:
- 'customtheme/scripts'
Your test function is not in the global scope.
If you want your test function to be able to be called from anywhere, don't put it in the $(document).ready or in the IIFE.
ie. in the first file, just have..
function test(){
console.log('hello);
}
You may also want to namespace your functions, but that is a separate question I suppose.
Also, for Drupal, you may be wanting to use drupal.behaviors rather than $(document).ready (for the second file)