Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Apress.Pro.Drupal.7.Development.3rd.Edition.Dec.2010.pdf
Скачиваний:
74
Добавлен:
14.03.2016
Размер:
13 Мб
Скачать
☆

CHAPTER 18 ■ USING JQUERY

■ Note We’re changing all the paragraph tags, so if you visit a node listing page such as http://example. com/?q=node, you’ll find that all paragraph tags, not just the ones in the teaser from your test page, are affected! In our example, we could limit the set of p tags being selected by changing our node. tpl.php template file to surround the content with <div class='standalone'> when the node is being displayed on a page by itself and starting the example with $(".standalone > p"). This query selects only the p elements that are descendents of elements within the standalone class.

Targeting an Element by ID

Let’s repeat our experiment, but this time target only the first paragraph, which we’ve identified with the ID of one:

<?php

drupal_add_js('jQuery(document).ready(function () { jQuery("#one").hide(); jQuery("#one").fadeIn("slow");

});', 'inline');

?>

<p id="one">Paragraph one</p> <p>Paragraph two</p> <p>Paragraph three</p>

■ Note Accessing an element by ID is one of the fastest selector methods within jQuery because it translates to the native JavaScript: document.getElementById("one"). The alternative, jQuery("p#one"), would be slower because jQuery needs to find all paragraph tags and then look for an intro ID. The slowest selector method in jQuery is the class selector jQuery".foo"), because a search would have to be made through all elements with the .foo selector class. (It would be faster to do jQuery"p.foo") in that case.)

Method Chaining

We can concatenate a series of jQuery methods because most methods within jQuery return a jQuery object. Let’s chain some methods together in a single jQuery command:

// Hide all the p tags, fade them in to visibility, then slide them up and down. jQuery("p").hide().fadeIn("slow").slideUp("slow").slideDown("slow");

jQuery calls are invoked from left to right. The preceding snippet finds all the paragraph tags, fades them in, and then uses a sliding effect to move the paragraphs up and then down. Because each of these

396

CHAPTER 18 ■ USING JQUERY

methods returns the jQuery wrapper object containing the same set it was given (all the p elements), we can manipulate the same set of elements over and over again until the final effect is achieved.

Adding or Removing a Class

jQuery can dynamically change the CSS class of an element. Here, we turn the first paragraph of our example red by selecting it by ID and then assigning Drupal’s error class to it:

jQuery("#one").addClass("error");

The counterpart to the addClass() method is the removeClass() method. The following snippet will remove the error class we just added:

jQuery("#one").removeClass("error");

And then there’s the toggleClass() method, which adds or removes a class each time it is called:

jQuery("#one").toggleClass("error"); // Adds class "error". jQuery("#one").toggleClass("error"); // Removes class "error". jQuery("#one").toggleClass("error"); // Adds class "error" again.

Wrapping Existing Elements

Instead of just adding an error class to the <p id="one"> element, let’s wrap that element in a div so that the red will show up better. The following jQuery snippet will do that:

<?php

drupal_add_js('jQuery(document).ready(function () { jQuery("#one").wrap("<div class=\'error\'></div>");

});', 'inline');

?>

<p id="one">Paragraph one</p> <p>Paragraph two</p> <p>Paragraph three</p>

Note the escaping of the single quotes, which is necessary because we already have open single quotes inside the drupal_add_js() function. The result of the div wrapping is shown in Figure 18-3.

397

CHAPTER 18 ■ USING JQUERY

Figure 18-3. The paragraph with ID “one” is wrapped in a div tag of class “error”.

Changing Values of CSS Elements

jQuery can be used to assign (or reassign) values to CSS elements. Let’s set the border surrounding the first paragraph to solid (see Figure 18-4):

jQuery("#one").wrap("<div class=\'error\'></div>").css("border", "solid");

Notice that the css method is still acting on the p element, not on the div element, because the wrap method returned the targeted p element after wrapping it.

Figure 18-4. The border property of the target element is changed.

The preceding examples have demonstrated some basic tasks that barely scratched the surface of what jQuery can do. You are urged to learn more at http://jquery.com/ or by picking up a good book on the subject.

398

CHAPTER 18 ■ USING JQUERY

Where to Put JavaScript

In the preceding examples, you have been testing jQuery by writing JavaScript in a node with the PHP filter enabled. While this is handy for testing, that’s not a good approach for a production site, where best practices dictate that the PHP filter be unavailable if at all possible. There are several different options for including JavaScript files in your Drupal site. For example, you can add them to your theme, include them from a module, or even include them but give others the option of modifying or overriding your code.

Adding JavaScript via a Theme .info File

The most convenient but least flexible way to include JavaScript files is to include a line in your theme’s

.info file. Let’s add an effect to your site that emphasizes the logo of your site by making it fade out and then fade in again when a page is loaded. Place the following JavaScript code in a file called logofade.js in your current theme. For example, if you are using the Bartik theme, it would be at themes/bartik/logofade.js.

//Selects the theme element with the id "logo", fades it out,

//then fades it in slowly.

jQuery(document).ready(function(){ jQuery("#logo").fadeOut("fast").fadeIn("slow");

});

The JavaScript file is in place; now we just have to tell Drupal to load it. Add the following line to your current theme’s .info file:

scripts[] = logofade.js

The last step is to make Drupal reread the .info file so that it will see that it needs to load logofade.js. To do that, go to Appearance, temporarily switch to a different theme, and then switch back.

This method of adding JavaScript is useful if the JavaScript will be loaded on every single page of your web site. In the next section, you’ll see how to add JavaScript only when a module that uses it is enabled.

A Module That Uses jQuery

Let’s build a small module that includes some jQuery functions in a JavaScript file. First, we’ll need a use case. Hmm, how about some JavaScript code that controls blocks? Blocks can be helpful in Drupal: they can show you your login status, tell you who’s new on the site or who’s online, and provide helpful navigation. But sometimes you just want to focus on the content of the page! Wouldn’t it be nice to hide blocks by default and show them only if you want to see them? The following module does just that, using jQuery to identify and hide the blocks in the left and right sidebar regions and providing a helpful button that will bring the blocks back. Here’s sites/all/modules/custom/blockaway.info:

399

Download from Wow! eBook <www.wowebook.com>

CHAPTER 18 ■ USING JQUERY

name = Block-Away

description = Uses jQuery to hide blocks until a button is clicked. package = Pro Drupal Development

core = 7.x files[]=blockaway.module

And here’s sites/all/modules/custom/blockaway.module:

<?php

/**

*@file

*Use this module to learn about jQuery.

*/

/**

* Implements hook_init(). */

function blockaway_init() {

drupal_add_js(drupal_get_path('module', 'blockaway') .'/blockaway.js');

}

All the module does is include the following JavaScript file, which you can put at sites/all/modules/custom/blockaway/blockaway.js:

/**

* Hide blocks in sidebars, then make them visible at the click of a button. */

jQuery(document).ready(function() {

//Get all div elements of class 'block' inside the left sidebar.

//Add to that all div elements of class 'block' inside the

//right sidebar. Check your theme’s page.tpl.php file to see what

//selectors you should use – the following are for garland.

var blocks = jQuery('#sidebar-first div.block, #sidebar-second div.block');

//Hide them. blocks.hide();

//Add a button that, when clicked, will make them reappear.

jQuery('#sidebar-first').prepend('<div id="collapsibutton">Show Blocks</div>'); jQuery('#collapsibutton').css({

'width': '90px', 'border': 'solid', 'border-width': '1px', 'padding': '5px', 'background-color': '#fff'

});

400

CHAPTER 18 ■ USING JQUERY

// Add a handler that runs once when the button is clicked. jQuery('#collapsibutton').one('click', function() {

//Button clicked! Get rid of the button. jQuery('#collapsibutton').remove();

//Display all our hidden blocks using an effect. blocks.slideDown("slow");

});

});

When you enable the module on the Modules page, any blocks you have visible should disappear and be replaced with a plain button, as shown in Figure 18-5.

Figure 18-5. A node being viewed with blockaway.module enabled

After clicking the button, the blocks should appear using a sliding effect, becoming visible as shown in Figure 18-6.

401

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]