Drupal 7 Tips: Fixing “$ is not an object” in JavaScript code

(I almost named this, “Drupal 7 wants you to use $ for money, not your jQuery.)

I ran into an API change issue yesterday when working on upgrading Fill PDF to be fully Drupal 7-compatible, and just today, someone on IRC ran into the same issue. She suggested that “somebody” write a blog post about it, so I thought I would. I hope it saves some random Internet searcher a few hairs.

Basically, you can no longer use jQuery’s shortcut variable $ in Drupal 7 instead of the full jQuery variable.

What does this mean? In short, code that you used to write like this:

$('#my-awesome-id').attr('title', 'My Awesome Title');

will net you a Javascript error in Drupal 7. There are not one, but two ways around this.

The Ugly Way

Replace $ with jQuery wherever $ is used. For example:

jQuery('#my-awesome-id').attr('title', 'My Awesome Title');

Yuck. Despite that actually being the slightly simpler way…I don’t like it.

The Money Way

This is the money way because it brings back the $. This way is slightly more complex because you have to wrap your JavaScript code inside of a parenthetical inline function. Let’s have a look:

(function($) {
$('#my-awesome-id').attr('title', 'My Awesome Title');

This basically makes $ work inside of that wrapper code (between the (function($) { and the })(jQuery). I haven’t yet tried putting it around entire JS files – if you have, let us know in the comments. Does Drupal.behaviors work inside of this wrapper? Update: According to Lê Thanh in the comments, Drupal.behaviors functions properly within the (function($) { … })(jQuery); wrapper. Next question – anyone know if this wrapper has a name? I’m going to call it the jQuery Sandwich ™ until corrected.

For the full story, see: http://drupal.org/node/224333#javascript_compatibility

And speaking of Drupal.behaviors, that has also changed a little bit (and perhaps more if you are doing AHAH/AJAX): http://drupal.org/node/224333#drupal_behaviors

Whether you write jQuery in Drupal 7 the subjectively ugly way or the subjectively money way, you will now at least be able to produce working jQuery code in Drupal 7. Happy coding!

P.S.: For further hair preservation, it is recommended not to look at the size of your browser scrollbar when browsing the “Converting 6.x modules to 7.x” page referenced above.

Update: P.P.S: The jQuery Sandwich is not actually a trademark, or if it is, it’s not mine.