jQuery not working in Drupal 7? $ is not a function?

Submitted on Wed, 06/15/2011 - 19:40

Well this one drove me nuts for a while. Why is jQuery not working in Drupal 7? For those of you writing custom jQuery for your theme or module, you might have experienced that you get the error “$ is not a function” in Drupal 7. “Don't bullshit me, $ is a function you smartass” was my first reaction to this. I was checking the sources and finding that jQuery loaded just fine, as it is of course in core.

The very simple solution is wrapping your jQuery in this pretty function:

(function ($) { 
  //jQuery code. Will proceed with a gif related example.
  $('#anigif').click(function () {
    $('#anigif2').slideToggle();
  });
  //End of gif related example. Put your code between these comments;
})(jQuery);

The reason you have to do this is because Drupal 7 wants to have a high compatibility with other javascript libraries, and so you can probably see why $ is not a function, although jQuery does indeed work in Drupal 7.

There are also other ways around this I guess, but this works for me.