6 min read

 

Drupal 6 Theming Cookbook

Drupal 6 Theming Cookbook

Over 100 clear step-by-step recipes to create powerful, great-looking Drupal themes

  • Take control of the look and feel of your Drupal website
  • Tips and tricks to get the most out of Drupal’s theming system
  • Learn how to customize existing themes and create unique themes from scratch
  • Part of Packt’s Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible
        Read more about this book      

(For more resources on Drupal, see here.)

Introduction

JavaScript libraries take out the majority of the hassle involved in writing code which will be executed in a variety of browsers each with its own vagaries. Drupal, by default, uses jQuery, a lightweight, robust, and well-supported package which, since its introduction, has become one of the most popular libraries in use today. While it is possible to wax eloquent about its features and ease of use, its most appealing factor is that it is a whole lot of fun!

jQuery’s efficiency and flexibility lies in its use of CSS selectors to target page elements and its use of chaining to link and perform commands in sequence. As an example, let us consider the following block of HTML which holds the items of a typical navigation menu.

<div class="menu">
<ul class="menu-list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>
</div>

Now, let us consider the situation where we want to add the class active to the first menu item in this list and, while we are at it, let us also color this element red. Using arcane JavaScript, we would have accomplished this with something like the following:

var elements = document.getElementsByTagName("ul");
for (var i = 0; i < elements.length; i++) {
if (elements[i].className === "menu-list") {
elements[i].childNodes[0].style.color = '#F00';
if (!elements[i].childNodes[0].className) {
elements[i].childNodes[0].className = 'active';
}
else {
elements[i].childNodes[0].className = elements[i].childNodes[0].
className + ' active';
}
}
}

Now, we would accomplish the same task using jQuery as follows:

$("ul.menu-list li:first-child").css('color', '#F00').
addClass('active');

The statement we have just seen can be effectively read as: Retrieve all UL tags classed menu-list and having LI tags as children, take the first of these LI tags, style it with some CSS which sets its color to #F00 (red) and then add a class named active to this element.

For better legibility, we can format the previous jQuery with each chained command on a separate line.

$("ul.menu-list li:first-child")
.css('color', '#F00')
.addClass('active');

We are just scratching the surface here. More information and documentation on jQuery’s features are available at http://jquery.com and http://www.visualjquery.com. A host of plugins which, like Drupal’s modules, extend and provide additional functionality, are available at http://plugins.jquery.com.

Another aspect of JavaScript programming that has improved in leaps and bounds is in the field of debugging. With its rising ubiquity, developers have introduced powerful debugging tools that are integrated into browsers and provide tools, such as interactive debugging, flow control, logging and monitoring, and so on, which have traditionally only been available to developers of other high-level languages. Of the many candidates out there, the most popular and feature-rich is Firebug. It can be downloaded and installed from https://addons.mozilla.org/en-US/ firefox/addon/1843.

Including JavaScript files from a theme

This recipe will list the steps required to include a JavaScript file from the .info file of the theme. We will be using the file to ensure that it is being included by outputting the standard Hello World! string upon page load.

Getting ready

While the procedure is the same for all the themes, we will be using the Zen-based myzen theme in this recipe.

How to do it…

The following steps are to be performed inside the myzen theme folder at sites/all/ themes/myzen.

  1. Browse into the js subfolder where JavaScript files are conventionally stored.
  2. Create a file named hello.js and open it in an editor.
  3. Add the following code:

    alert("Hello World!!");

  4. Save the file and exit the editor.
  5. Browse back up to the myzen folder and open myzen.info in an editor.
  6. Include our new script using the following syntax:

    scripts[] = js/hello.js

  7. Save the file and exit the editor.
  8. Rebuild the theme registry and if JavaScript optimization is enabled for the site, the cache will also need to be cleared.
  9. View any page on the site to see our script taking effect.

How it works…

Once the theme registry is rebuilt and the cache cleared, Drupal adds hello.js to its list of JavaScript files to be loaded and embeds it in the HTML page. The JavaScript is executed before any of the content is displayed on the page and the resulting page with the alert dialog box should look something like the following screenshot:

Using JavaScript and jQuery in Drupal Themes

There’s more…

While we have successfully added our JavaScript in this recipe, Drupal and jQuery provide efficient solutions to work around this issue of the JavaScript being executed as soon as the page is loaded.

Executing JavaScript only after the page is rendered

A solution to the problem of the alert statement being executed before the page is ready, is to wrap our JavaScript inside jQuery’s ready() function. Using it ensures that the code within is executed only once the page has been rendered and is ready to be acted upon.

if (Drupal.jsEnabled) {
$(document).ready(function () {
alert("Hello World!!");
});
}

Furthermore, we have wrapped the ready() function within a check for Drupal.jsEnabled which acts as a global killswitch. If this variable is set to false, then JavaScript is turned off for the entire site and vice versa. It is set to true by default provided that the user’s browser meets Drupal’s requirements.

Drupal’s JavaScript behaviors

While jQuery’s ready() function works well, Drupal recommends the use of behaviors to manage our use of JavaScript. Our Hello World example would now look like this:

Drupal.behaviors.myzenAlert = function (context) {
alert("Hello World!!");
};

All registered behaviors are called automatically by Drupal once the page is ready. Drupal.behaviors also allows us to forego the call to the ready() function as well as the check for jsEnabled as these are done implicitly.

As with most things Drupal, it is always a good idea to namespace our behaviors based on the module or theme name to avoid conflicts. In this case, the behavior name has been prefixed with myzen as it is part of the myzen theme.

LEAVE A REPLY

Please enter your comment!
Please enter your name here