Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JQuery in Drupal 7

I'm writing my own Drupal 7 module, and like to use JQuery in it.

$('#field').toggle(); 

But I'm getting this error:

TypeError: Property '$' of object [object DOMWindow] is not a function 

It seems that JQuery is not loaded. Otherwise $ should be defined.

Though I actually include it in the header:

<script type="text/javascript" src="http://rockfinder.de/misc/jquery.js?v=1.4.4"></script> 

Do I have to do anything else to activate JQuery in Drupal? Is $ being overwritten by Drupal?

That's the website: http://rockfinder.orgapage.de

like image 671
JochenJung Avatar asked Jan 13 '11 14:01

JochenJung


People also ask

Does Drupal use jQuery?

In addition to custom JavaScript files many Drupal developers find jQuery useful. jQuery is a lightweight JavaScript library which is built into Drupal. jQuery contains all the common DOM, event, effects, and Ajax functions. Drupal 7 includes jQuery 1.4.

Is Drupal 7 outdated?

Drupal 7, first released in January 2011, is now approaching its end of life, set for November 2023. At that time, official Drupal 7 support from the Drupal community will end, including support for updates, security fixes, and enhancements from the Drupal Association and the Drupal Security Team.

Can you use JavaScript with Drupal?

Since Drupal 8, the available JavaScript files, which were referenced in . info files in Drupal 7, are now referenced in . yml files. Also, stylesheets (CSS) and JavaScript (JS) are loaded through the same system as modules (code) and themes: asset libraries.


1 Answers

From the Drupal 7 upgrade guide:

Javascript should be made compatible with other libraries than jQuery by adding a small wrapper around your existing code:

(function ($) {   // Original JavaScript code. })(jQuery); 

The $ global will no longer refer to the jquery object. However, with this construction, the local variable $ will refer to jquery, allowing your code to access jQuery through $ anyway, while the code will not conflict with other libraries that use the $ global.

You can also just use the 'jQuery' variable instead of the $ variable in your code.

like image 91
Eaton Avatar answered Sep 30 '22 19:09

Eaton