[Drupal] How to add js file to a Drupal module

| | 1 min read

In Drupal you can attach a js file in different ways. First by adding it to your theme's info file. Adding js to your theme's info file to call the js files in all pages.

scripts[] = js_filename.js

Another method is to use drupal_add_js(),which add the js file to the particular pages specified in the function such as, the pages in the specified module.

drupal_add_js(drupal_get_path('module', 'module_name') .'/path/to/js_filename.js', array('type' => 'file', 'scope' => 'header'));

In order to attach js behavior to a form you can use #attached attribute on of the form items.

$form['#attached']['js'] = array(
  drupal_get_path('module', 'module_name') . '/path/to/js_filename.js',
);

To attach an external js link to the form you can use the following code.

$form['#attached']['js'] = array(
  'http://code.jquery.com/jquery-1.4.2.min.js' => array(
    'type' => 'external',
  ),
);

To attach an inline js code to the form you can use the following code.

$form['#attached']['js'][] = array(
      'data' => 'your_inline_code',
      'type' => 'inline',
    )
);
 

 

Zyxware is a leading Drupal development company with a team of high expertise in Drupal custom module development services since 2006.