18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

• jQuery Form, a plugin to easily and unobtrusively upgrade HTML forms to<br />

use AJAX<br />

• iQuery Once, which filters out all elements that had the same filter applied to<br />

them previously<br />

• jQuery BBQ, a back button and query library<br />

• Farbtastic, a color wheel<br />

Adding JavaScript<br />

Most of the JavaScript written for <strong>Drupal</strong> utilizes jQuery but it is not a requirement.<br />

When JavaScript is added to the page there are some things to be aware of.<br />

<strong>Drupal</strong> sets jQuery up to use its no conflict mode. This means that the $ variable is<br />

relinquished so <strong>Drupal</strong> can work with other JavaScript libraries that may use the $<br />

variable. More detail is available at http://api.jquery.com/jQuery.noConflict.<br />

In the absence of $ there are two methods for writing JavaScript that use jQuery. The<br />

first is to use jQuery in any place where you may have used the $. For example:<br />

jQuery().ready(function() {<br />

...<br />

});<br />

The other way is to wrap your code in an anonymous function and choose an alias.<br />

For example:<br />

(function($) {<br />

$().ready(function() {<br />

...<br />

});<br />

})(jQuery);<br />

In this case jQuery is passed in with the alias of $. Technically, $ can be replaced<br />

with a different valid alias of your choice. This works for JavaScript within a file or<br />

when placed inline on the page.<br />

<strong>Drupal</strong> has the ability to preprocess JavaScript files where multiple files are<br />

converted into fewer files. Preprocessing provides a performance improvement for<br />

end uses as they have fewer files to download. For the preprocessor to create valid<br />

JavaScript it is recommended that at places where optional JavaScript semicolons<br />

are allowed, they should be used. In the preceding example, the semicolon after the<br />

closing (jQuery) is an example of where to use the optional semicolons.<br />

[ 288 ]

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

Saved successfully!

Ooh no, something went wrong!