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.

Chapter 10<br />

Adding JavaScript and CSS files to .info files<br />

The simplest method to add JavaScript and CSS to a page is by adding them to the<br />

.info files for a module. When JavaScript and CSS files are specified in a .info file they<br />

are added to all pages and configured to use preprocessing (more on that later). An<br />

example that adds a script and CSS file looks like:<br />

scripts[] = foo.js<br />

stylesheets[screen][] = bar.css<br />

Each of these is a file and the path is relative to the root of the module. The scripts<br />

property is an array of script files. The stylesheets property is an array of media<br />

types and each media type is an array of CSS files.<br />

Using drupal_add_js()<br />

The most common method of adding JavaScript to a page is by using the function<br />

drupal_add_js(). This utility function provides the ability to add files (both<br />

external to <strong>Drupal</strong> and within the file system), add inline JavaScript, and pass<br />

variables between PHP and JavaScript.<br />

Typically Cascading Stylesheets (CSS) are used alongside JavaScript. <strong>Drupal</strong> provides<br />

a function to add CSS to a page that works in a fashion similar to drupal_add_js().<br />

It's called drupal_add_css(). The APIs between the two functions are almost<br />

identical. The feature set differs in that CSS doesn't have variables to pass in from<br />

PHP and stylesheets have media and Internet Explorer options.<br />

Through the examples in this chapter we will create a Hello World module that<br />

displays Hello World in various ways using JavaScript. The function definition for<br />

drupal_add_js() provides two arguments with varying values depending on what<br />

you are doing with it. The definition is:<br />

function drupal_add_js($data = NULL, $options = NULL)<br />

As we work through the Hello World module we will examine the different<br />

variances and possible values which can be passed into drupal_add_js().<br />

Adding JavaScript files<br />

Adding a file is the default behavior of drupal_add_js() and drupal_add_css().<br />

Adding a JavaScript file and a CSS file to a page would look like the following:<br />

drupal_add_js('path/to/hello_world.js');<br />

drupal_add_css('path/to/hello_world.css');<br />

[ 289 ]

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

Saved successfully!

Ooh no, something went wrong!