06.05.2013 Views

Drupal 6 JavaScript and jQuery - Ebook-Cours.com

Drupal 6 JavaScript and jQuery - Ebook-Cours.com

Drupal 6 JavaScript and jQuery - Ebook-Cours.com

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

[ 317 ]<br />

Chapter 9<br />

That's all there is to this anonymous function executed by the $().each() function.<br />

There's only one more thing our plug-in function does:<br />

(function ($) {<br />

<strong>jQuery</strong>.fn.divWrap = function () {<br />

var attrs = (arguments.length > 0) ? arguments[0] : {};<br />

this.each(function (index, item) {<br />

var div = $(item).wrap('').parent();<br />

if (attrs) {<br />

div.attr(attrs);<br />

}<br />

});<br />

return this;<br />

}<br />

})(<strong>jQuery</strong>);<br />

Notice the highlighted line in the code? Why do we return this? We are returning<br />

the <strong>jQuery</strong> object so that other functions can be chained off to this one. We could, for<br />

example, do something like this:<br />

$('a').divWrap().text();<br />

This would return the text of each element after wrapping all of the<br />

elements inside of the div tags.<br />

So that's the basic method for creating a <strong>jQuery</strong> plug-in. How do you make use of<br />

this tool inside of <strong>Drupal</strong>? This is done the same way you would use any <strong>JavaScript</strong><br />

library. In a theme, you might add it to the .info file using a scripts[] directive.<br />

Or in PHP (such as a module), you can add it with the drupal_add_js() function.<br />

Other references for writing <strong>jQuery</strong> plug-ins<br />

There are two very helpful <strong>jQuery</strong> basic plug-in writing tutorials<br />

that may be helpful. The official plug-in writing guide is at http://<br />

docs.jquery.<strong>com</strong>/Plug-ins/Authoring. The st<strong>and</strong>ard plug-in<br />

writing pattern is explained here: http://www.learningjquery.<br />

<strong>com</strong>/2007/10/a-plug-in-development-pattern.<br />

When should you write a <strong>jQuery</strong> plug-in instead of <strong>JavaScript</strong> in <strong>Drupal</strong>? To<br />

a large extent, the answer will depend on your own needs. However, here are<br />

some guidelines:<br />

•<br />

If you might need to use the code outside of <strong>Drupal</strong>, a plug-in is easier<br />

to port. In fact, you may want to release a generic plug-in to the <strong>jQuery</strong><br />

<strong>com</strong>munity at http://jquery.<strong>com</strong>.<br />

This material is copyright <strong>and</strong> is licensed for the sole use by Richard Ostheimer on 18th June 2009<br />

2205 hilda ave., , missoula, , 59801

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

Saved successfully!

Ooh no, something went wrong!