Using jQuery in Drupal

So far, we have seen just a few lines of jQuery code. But, our examples have been independent of Drupal. How can we use jQuery inside of Drupal?

The answer is simple. If we write our JavaScript "the Drupal way", then Drupal will make it very easy to use jQuery. Here's what I mean.

How do we include JavaScript files in Drupal themes? By using the scripts[] directive in the theme's .info file. And if you're a PHP programmer, you can use the drupal_add_js() function in either a theme or a module.

If you use either of these means, then Drupal will automatically include the basic JavaScript libraries, including drupal.js and jquery.js. That's right. Drupal not only includes jQuery in its core distribution, but automatically includes it for you.

To see an example of this, we need not look further than the code we wrote in the previous chapter. Looking in the <head></head> section of the HTML for our theme, we can see the following <script></script> tags:

<script type="text/javascript"

src="/drupal/misc/jquery.js"></script> <script type="text/javascript"

src="/drupal/misc/drupal.js"></script> <script type="text/javascript"

src="/drupal/sites/all/themes/frobnitz/printer_tool.js"> </script>

<script type="text/javascript">

jQuery.extend(Drupal.settings, { "basePath": "/drupal/" }); </script>

All we added to our .info file was scripts[] = printer_tool.js. Drupal took care of adding the other two script files. But what is that last section? Well it is:

jQuery.extend(Drupal.settings, { "basePath": "/drupal/" });

This is another use of jQuery. It provides a few functions for extending an object, which assigns new attributes to an existing object on the fly.

In this case, the extend() function is taking the Drupal.settings object and adding a new property, basePath, with the value /drupal/. Here, /drupal/ is the absolute web path to Drupal. That is, my Drupal installation resides at http://localhost/ drupal/. The basePath property can then be used for constructing URLs.

Using the Firebug console, we can see the result of this extension. If we enter Drupal.settings.basePath on the console, Firebug will print /drupal/.

Using the jQuery object without constructing a new instance

In the Drupal-generated code that we just saw, you might notice that jQuery was referenced as an object, not as a function (note the missing parentheses after jQuery). Some jQuery functions do not need a list of elements or other contents before they can operate. Effectively, they can be used as static functions. The extend() function is such an example. In such cases, we don't need to build a new jQuery object. We can just use the main jQuery object.

The point to be made here is simply this: When we allow Drupal to manage our JavaScript, it handles the basic including necessary to make use of jQuery, and even initializes some things for us.

Of course, there's a converse side to this.

+2 0

Post a comment