Include JS function from other JS file

Public

This is a snippet how to include a Javascript function from module A in module B (Drupal 7)

Get raw version
javascript
  1. 1. ) Be sure you have included JS files in your Drupal module files.
  2.  
  3. $form['#attached']['js'][] = drupal_get_path('module', 'module_A') . '/module_A.js';
  4. $form['#attached']['js'][] = drupal_get_path('module', 'module_B') . '/module_B.js';
  5.  
  6. 2. ) module_A.js file
  7.  
  8. (function ($) {
  9. Drupal.behaviors.module_A = {};
  10. Drupal.behaviors.module_A.my_function = function(selector) {
  11. // Your code.
  12. }
  13. })(jQuery);
  14.  
  15. 3. ) Call the function in module_B.js file
  16. (function ($) {
  17. Drupal.behaviors.module_B = {};
  18. Drupal.behaviors.module_B.attach = function(context) {
  19.  
  20. // This is the main part here. You have to respect the namespace of module A.
  21. Drupal.behaviors.module_A.my_function('.my-selector');
  22. }
  23. })(jQuery);