18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

JavaScript in <strong>Drupal</strong><br />

Settings should be added in a way that respects the namespacing of other settings<br />

added to the page. Passing multiple settings should be done in a nested array.<br />

For example:<br />

$settings = array(<br />

'helloWorld' => array(<br />

'display' => 'alert',<br />

'message' => 'Hello World!',<br />

),<br />

);<br />

drupal_add_js($settings, 'setting');<br />

In this example, the message is available at <strong>Drupal</strong>.settings.helloWorld.message.<br />

Keeping all the settings in <strong>Drupal</strong>.settings.helloWorld, keeps the settings for this<br />

module separate from the settings added by other modules.<br />

Adding inline JavaScript<br />

JavaScript can be added inline on the page using the inline option. An example<br />

that alerts "Hello World!" would look like:<br />

drupal_add_js('alert("Hello World!");', 'inline');<br />

The options accessible to inline JavaScript are defer, group, every_page,<br />

weight, and scope. Inline JavaScript is not cached by the browser and cannot be<br />

preprocessed. Inline JavaScript that is added, which defers until after the browser<br />

has loaded with a weight of JS_THEME would look like this:<br />

$options = array(<br />

'type' => 'inline',<br />

'group' => JS_THEME,<br />

'defer' => TRUE,<br />

);<br />

drupal_add_js("alert('Hello World!')", $options);<br />

API Documentation for drupal_add_js() is available at<br />

http://api.drupal.org/api/function/drupal_add_js/7<br />

Adding inline CSS<br />

CSS can also be added inline and the API is similar to the one for JavaScript. To add<br />

inline CSS it would look like this:<br />

drupal_add_css("body { color: #ffffff; }", 'inline');<br />

[ 294 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!