How to add values to Drupal.settings using the function drupal_add_js()?

| | 1 min read

drupal_add_js() function is mainly used to add JavaScript to the page, either as reference to an existing file or as in-line code (by writing the code directly in the page). But it also add settings to Drupal's global storage of JavaScript settings. These settings can access using Drupal.settings variable in JavaScript file.

Let's look at a simple example to add a custom setting to the JavaScript Drupal.settings variable. We can set values like this in your module file.

drupal_add_js(
  array(
    'module_name' => array(
      'count' => $count,
    )
  ),
  'setting'
  );

The variable will be available in Drupal.settings in our jquery script , like this:

(function ($) {
  Drupal.behaviors.example_name = {
    attach: function(context) {
      var count = Drupal.settings.module_name.count;
    }
  }
})(jQuery);

In Drupal 7 you can write code like this

Drupal.behaviors.module_name = {
  attach: function(context, settings) {
    var count = settings.count;
  }
}

If you want to know more about the usage of drupal_add_js() function, please drop us a line. For further help or assistance, check this out.