[Drupal] A Good way to add jQuery to Drupal 7

| | 2 min read

In order to add a new jQuery or multiple javaScript/CSS to the Drupal site, it is better to use hook_library rather than using drupal_add_css/drupal_add_js multiple times. It is helpful if we are using the javaScript/CSS in multiple pages.

A good way of adding a jquery to drupal is creating a library for that jquery by including all the required css and javascripts. It will help to load the library on demand. And also avoid the usage of multiple drupal_add_js/drupal_add_css functions.

The hook_library creates a library with a set of javaScripts and CSS. In other words, hook_library registers javaScript/CSS as module specific or library specific. Then such a library can be added using the drupal_add_library() without having to add multiple files in a library seperately. By using drupal_add_library(), it will avoid loading the library when not necessary.The hook_library has the flexibility of the drupal_add_css/drupal_add_js for adding inline, external script or javascript settings.

The following code shows an implementation of the hook_library to add the spinner jQuery to the textboxes in specific pages. In this function we create the library as an associative library.


function my_module_library() {
  $libraries['jquery_ui_spinner'] = array(
    'title' => 'jQuery Spinner',
    'website' => 'http://jqueryui.com/spinner/',
    'version' => '1.20',
    'js' => array(
      libraries_get_path('jquery_ui_spinner') . '/ui.spinner.min.js' => array(),
    ),
    'css' => array(
      libraries_get_path('jquery_ui_spinner') . '/ui.spinner.css' => array(),
      libraries_get_path('jquery_ui_spinner') . '/jquery-ui.css' => array(),
    ),
    'dependencies' => array(
      array('system', 'ui.widget'),
    ),
  );
  return $libraries;
}

The contents of the assossiative array includes :

  • title : Human readable title for the library.
  • website : The library website URL.
  • version : version of the jQuery.
  • js : It is an array of javaScripts. In the case of module specific library, the keys are the paths of the javaScript files ie. the $data argument, and the values of the array is the $option argument of drupal_add_js function.
  • css : It is an array of CSS passed to drupal_add_css.
  • dependencies : It is the array of libraries required of this library.

We can add the library either by using the drupal_add_library() function or by using the #attached property.


drupal_add_library('fitshares', 'jquery_ui_spinner')

form['#attached']['library'][] = array('fitshares', 'jquery_ui_spinner')