Advertising sustains the DA. Ads are hidden for members. Join today

HowTos

How to add jQuery UI libraries to a page

Last updated on
1 November 2016

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

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.

function mymodule_form_contact_site_form_alter(&$form, &$form_state, $form_id) {
  $path = drupal_get_path('module', 'mymodule');
  
  // 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)

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

Help improve this page

Page status: No known problems

You can: