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

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

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

<strong>jQuery</strong>: Do More with <strong>Drupal</strong><br />

Unfortunately, the two popular ways of ac<strong>com</strong>plishing this have<br />

significant drawbacks.<br />

The first method of calling the init() method is to embed a snippet of <strong>JavaScript</strong><br />

somewhere in the page. For example, a section of code like this might be inserted<br />

somewhere in the document's body:<br />

<br />

StickyRotate.init()<br />

<br />

What's wrong with this? For starters, it's messy. In order to make sure that it is<br />

executed correctly, we have to put the script somewhere in the HTML after the<br />

last sticky node. Otherwise, we run the risk of having the script execute before the<br />

HTML is <strong>com</strong>pletely loaded. This means that we have to hack the page.tpl.php file<br />

to insert the code in the appropriate place. This, in turn, can end up being a pain to<br />

maintain (<strong>and</strong> it is not very portable).<br />

Instead, we might try to fire the event by adding onload="StickyRotate.init()"<br />

to the element. This has two drawbacks. First, it means we have<br />

to hack page.tpl.php, which is undesirable. Second, onload is not implemented<br />

consistently across browsers, <strong>and</strong> it may take longer to fire than we would like<br />

(or it may fire before the document is really ready).<br />

Fortunately for us, <strong>jQuery</strong> provides a third alternative. We can write a few lines<br />

of <strong>JavaScript</strong> that will attach an event h<strong>and</strong>ler to a special <strong>jQuery</strong> ready event.<br />

According to the <strong>jQuery</strong> documentation, the ready event is fired the instant the DOM<br />

is ready to be read <strong>and</strong> manipulated. (See http://docs.jquery.<strong>com</strong>/Events/ready<br />

for details.)<br />

Here <strong>and</strong> throughout the book, we will use this method to execute code as soon as<br />

we can reliably do so.<br />

Here's how we will do it for our present code:<br />

$(document).ready(StickyRotate.init);<br />

This code doesn't go in the HTML body, <strong>and</strong> does not need to be launched<br />

from onload or another HTML attribute. Instead, it is included in our<br />

sticky_rotate.js file.<br />

Here's how this line works.<br />

[ 90 ]<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!