0

I'm building a module with a basic form. This form has some js attached to it that I want to keep in the module, so that it's not cluttering my regular scripts file. How do I add it to my module?

I tried to add this is in my .module file but no luck.

function mymodule_init() {
drupal_add_js(drupal_get_path('module', 'mymodule') .'/myscriptfile.js');
}

What should I do?

1
3

You can declare the script file inside mymodule.info with

scripts[] = myscriptfile.js

This way it's gonna be included in every page of your site, exactly the same result you obtain adding it manually to hook_init.

In case you want it only when you render a form, add this to the form declaration

$form['#attached']['js'][] = drupal_get_path('module', 'mymodule).'myscriptfile.js';
2
  • Ok. I don't really want it on every site though. I would like it to only appear on the page that the module block is rendered on. The js contains some validation and other related stuff that only applies to the form that the module builds. So it's unnecessary to render it in other places. What's the best way to do this then? – Johan Dahl Apr 8 '14 at 14:45
  • In that case the solution is similar to the other answer – Astrayus Apr 8 '14 at 14:56
0

In a form you can set an #attached value. This value will allow you to attach javascript or css to the form.

I believe that is the best way. Here is an example below. (taken from drupal.org)

$form['#attached']['js'] = array(
  drupal_get_path('module', 'ajax_example') . '/ajax_example.js' => array(
  'type' => 'file',
  ),
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.