AJAX and AHAH for Drupal themers.

Harnessing the Power of Drupal.behaviors and Drupal.attachBehaviors

One of the most frustrating situations I've run into in Drupal has been how to make use of jQuery AJAX/AHAH calls in a theme (will just call it AJAX for simplicity's sake). I say frustrating because we have all the tools we need to accomplish this task out-of-the-box in Drupal. We have jQuery, we can easily add custom .js files in the theme and we have nearly endless control over the display of information that we want to use through templating, CCK, Views, Context, etc.

So, if you're comfortable writing AJAX calls in jQuery (something which they made remarkably simple and is well documented), you of course can just add the js to your script file and poof! ...like magic, you're doing AJAX in Drupal. You feel like a ninja, like anything is possible, until... you don't. Because any HTML you grab from another page that has javascript events attached is suddenly event-less after your AJAX call. For example, you grab a slideshow or even just a link with a click event on it and all of a sudden after your AJAX retrieves that info, the javascript is absent. This may sound like an edge-case, but you'd be amazed how much of the content you want to grab needs these events. If you're like me, you might be thinking at this point: "But I can make those events run regardless of when they are used using the .live event." This is true, but in a CMS-powered site, how many of these calls can you really have that kind of control over? Typically, you're leveraging other modules to create these script-driven areas of your site, e.g., Views Slideshow to create a slideshow. So, just as quickly as you feel powerful, the power seems gone.

Bad turns to worse when you realize there is also very little documentation on drupal.org about this. Most articles there for creating AJAX driven applications are geared toward module developers and in turn can be confusing for front-end developers and just don't speak directly to this task. Thankfully, I was able to extract from this documentation and a couple of helpful blog posts - here and here (and a little trial/error) the very simple solution to this.

Drupal.behaviors and Drupal.attachBehaviors

While the documentation for this might be lacking, the code is very much not. In fact, the jQuery/javascript built into core Drupal (drupal.js) has an incredibly powerful way of dealing with this. So let's get to it.

Basically, for any script that needs to be run following an AJAX event, wrap it in a Drupal.behaviors function.

Drupal.behaviors.[YOURFUNCTIONNAME] = {
  attach: function(context) {
  }
};
or in Drupal 6:
Drupal.behaviors.[YOURFUNCTIONNAME] = function() {}

This in turn tells Drupal to store this as a behavior that can then be run every time the function Drupal.attachBehaviors is run.

Drupal.attachBehaviors()

Thankfully, most module developers are aware of this and rather than wrapping their functions in the general jQuery function, they wrap them as a behavior. What's awesome is we can use this same code just as easily in the theme layer.  Here's a simple example:

Drupal.behaviors.thisIsABehaviorINeedToRunAfterAjaxCall = {
  attach: function(context) {  
  //jQuery/javascript events here.
} };
or in Drupal 6:
Drupal.behaviors.thisIsABehaviorINeedToRunAfterAjaxCall = function()
//jQuery/javascript events here.
}
// Then, once you've made your AJAX call, include this in your callback:
Drupal.attachBehaviors('Whatever element needs to have those scripts reattached');

So, instead of wrapping custom jQuery/javascript in your local .js file with a general jQuery function (e.g., beginning with $(function() {...), wrap it as a behavior if you need it after an AJAX call is made.  And once your AJAX call is made, simply run Drupal.attachBehaviors on whatever element needs to have these behaviors assigned. Voila!

And now, your ability to run AJAX/AHAH in the theme layer is truly limitless. Try it! It's a wonderful feeling.

Comments

Hi there to all, because I am in fact keen of reading this weblog's post to be updated regularly. It carries nice material.

I think the admin of this website is truly working hard in support
of his website, for the reason that here every stuff is quality based material.

Attractive part of content. I simply stumbled upon your site
and in accession capital to say that I get in fact loved account your blog
posts. Anyway I'll be subscribing on your augment and even I
achievement you access consistently quickly.

I do not comment, however after looking at a few of the comments on this page Add new comment | EvanWillhite.com - Development,
Design and Drupal. I actually do have a couple of questions for you if it's allright.

Is it just me or do a few of the remarks come across like they are coming from brain
dead people? :-P And, if you are writing at additional online social
sites, I'd like to follow anything fresh you have to post.

Would you post a list of the complete urls of all your public pages
like your twitter feed, Facebook page or linkedin profile?

Way cool! Some very valid points! I appreciate you penning this write-up
plus the rest of the site is really good.

Hi! Do you know if they make any plugins to assist with Search
Engine Optimization? I'm trying to get my blog to rank for some targeted keywords but
I'm not seeing very good gains. If you know of any
please share. Many thanks!

Hello there, I do believe your website may be having browser compatibility issues.

When I take a look at your web site in Safari, it looks
fine but when opening in Internet Explorer, it's got
some overlapping issues. I just wanted to provide you with a
quick heads up! Apart from that, excellent site!

Hey There. I discovered your weblog the usage of msn. This is an extremely smartly written article.
I'll be sure to bookmark it and come back to learn more of your useful information.
Thank you for the post. I'll certainly comeback.

I'm truly enjoying the design and layout of your blog.
It's a very easy on the eyes which makes it much more pleasant for me to come here and visit more often.
Did you hire out a developer to create your theme? Great work!

This is a good tip especially to those new to the blogosphere.
Short but very precise information… Thanks for sharing this
one. A must read post!

Hello, after reading this remarkable paragraph i am as well delighted to share my experience
here with colleagues.

I've been surfing on-line more than three hours lately, but I never discovered any interesting article like yours.
It's pretty worth enough for me. Personally, if all site owners and bloggers made just right content material as you probably did,
the web will probably be much more helpful than ever before.

Hi there Dear, are you really visiting this website regularly, if so after that you will without doubt
get pleasant experience.

Hello i am kavin, its my first occasion to commenting anywhere,
when i read this paragraph i thought i could also create
comment due to this sensible piece of writing.
My website csiaspb.org

I am genuinely thankful to the owner of this web site
who has shared this wonderful piece of writing at here.

Wow! After all I got a website from where I know how to genuinely take valuable information concerning my study and knowledge.

Awesome issues here. I am very glad to see your article.
Thanks so much and I'm looking forward to touch you. Will you kindly drop me a mail?

What's Going down i am new to this, I stumbled upon this I've discovered It absolutely helpful and it has aided me out loads.

I am hoping to give a contribution & aid different users like its
helped me. Great job.

Hmm is anyone else encountering problems with the pictures on this blog loading?

I'm trying to determine if its a problem on my end or if it's the blog.
Any feed-back would be greatly appreciated.

When someone writes an paragraph he/she retains the plan of a user
in his/her mind that how a user can be aware of it. So that's why this
post is outstdanding. Thanks!

Pretty nice post. I just stumbled upon your weblog and wished to say that I've really enjoyed browsing your blog posts.
In any case I'll be subscribing to your rss feed and I hope you
write again soon!

I am regular reader, how are you everybody? This piece of writing posted at this site is
actually good.

Kart pożyczka. Jednak zachciej pomnieć o spłacie
obciążenie, należnoście świadczy o wzrosła liczba tudzież warto skorzystanie repertuar zadłużenie,
o do tego stopnia zmieścimy się tym przyznawania przelewy jako interes bezgotówkowych pula, limicie oraz należnoście świadczy o wzrosła wolumen i należałoby skorzystanie skutkuje nam.

Wow, marvelous weblog layout! How long have you been running a blog for?
you make running a blog look easy. The whole look of your web site is wonderful, as neatly as the content material!

Today, while I was at work, my sister stole my iPad and
tested to see if it can survive a 30 foot drop, just so she can be a youtube sensation.
My apple ipad is now broken and she has 83 views. I know this is completely
off topic but I had to share it with someone!

Hi to all, since I am in fact eager of reading this webpage's post to be updated on a regular basis.
It contains fastidious data.

I'm impressed, I have to admit. Seldom do I encounter a blog that's both
equally educative and interesting, and let me tell you,
you have hit the nail on the head. The issue is something which too few people
are speaking intelligently about. I'm very happy that I came across this in my search for something
relating to this.

Why viewers still use to read news papers when in this technological world
the whole thing is available on net?

Everything is very open with a really clear description of
the issues. It was truly informative. Your website is very useful.
Thanks for sharing!

My brother suggested I may like this web site. He used to
be entirely right. This post truly made my day. You can not imagine simply how so much time I had spent for this information!
Thank you!

Wonderful blog! I found it while browsing on Yahoo News. Do you have any
suggestions on how to get listed in Yahoo News? I've been trying for a while
but I never seem to get there! Appreciate it

I'm not sure where you're getting your information, but good topic.
I needs to spend some time learning much more or understanding more.
Thanks for magnificent info I was looking for this info for my mission.

Hi there, I enjoy reading through your article post. I like to write a little
comment to support you.

Your style is very unique in comparison to other folks I've read stuff from.

Thanks for posting when you've got the opportunity,
Guess I will just bookmark this page.

63a4 Michael Kors purses
6k8 3c1 7i2
pH2014baby1eByEast q604u

Add new comment