Last updated June 7, 2014. Created on March 20, 2014.
Edited by acabouet, Bevan, AnthonyBartoli. Log in to edit this page.

Drupal 7 ships with jQuery UI 1.8.7, so you don't need to add the actual library code unless you wish to use a different version. jQuery UI runs on top of jQuery which also ships with Drupal. jQuery is loaded by default on all pages but jQuery UI libraries must be manually enabled.

A jQuery UI library can be included either with drupal_add_library() or drupal_add_js() (deprecated) or by adding it to the #attached property of renderable arrays (recommended).

This article demonstrates both approaches, but drupal_add_library() and drupal_add_js() will not be available in Drupal 8.

Although a given library may depend on a number of other libraries, you only need to add the library you wish to use. The dependencies are automatically included.

The example below adds the autocomplete library to a new field on the site contact form.

1. Using #attached in a renderable array (recommended)

<?php
function mymodule_form_contact_site_form_alter(&$form, &$form_state, $form_id) {
 
$path = drupal_get_path('module', 'jqueryui');
 
 
// Adds a form field that the javascript utilizes or modifies.
 
$form['location'] = array(
   
'#type' => 'textfield',
   
'#title' => 'Your Location (Country)',
   
'#id' => 'country_autocomplete',
   
// Both the library and custom JavaScript code are added to the '#attached'
    // property of a renderable array.
   
'#attached' => array(
     
'library' => array(
        array(
'system', 'ui.autocomplete'),
      ),
     
'js' => array(
       
"$path/mymodule-custom-javascript.js",
      ),
    ),
  );
}
?>

2. Using drupal_add_library() (deprecated)

<?php
function mymodule_form_contact_site_form_alter(&$form, &$form_state, $form_id) {
 
// Adds a form field that the javascript utilizes or modifies.
 
$form['location'] = array(
   
'#type' => 'textfield',
   
'#title' => t('Your Location (Country)'),
   
'#id' => 'country_autocomplete',
  );

 
// Adds the library making it available for use.
 
drupal_add_library('system', 'ui.autocomplete');
 
 
// Custom JavaScript code that uses the library.
 
$path = drupal_get_path('module', 'mymodule');
 
drupal_add_js("$path/mymodule-custom-javascript.js");
}
?>

Further Reading

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.

Comments

dskanth’s picture

Here is an example of adding Jquery UI Accordion support to your form, via hook_form_alter(), assuming that Jquery Update module is installed and enabled in Drupal7.

$form['field_stages']['#attached'] = array(
'library' => array(
array('system', 'ui.accordion')
)
);

PHP Developer

hd_sali’s picture

Hello,

I wanna add a batch of js files in my home page!
anybody's help would be appriciated.

Thank you in advance