jQuery and Drupal 7
So it turns out jquery is easy. I can't believe I have gone this long as a Drupal themer and not bothered to try jquery. I saw all these $ and () and just figured it would be complicated.
Well I been messing around on jsfiddle.net, making some pretty interesting things - ex. http://jsfiddle.net/tesliker/L9uPm/3/ , but then I turned my sights back to integrating this with Drupal. This is where I had some trouble. Besides the fact I always forget to run cron after adding new JS and CSS stylesheets, it turns out you have to wrap your jquery in a special wrapper so that the $ variable does not confuse Drupal. Anyways, here is what I ended up doing to get this up and running correctly.
I added my custom module.
I named it custom_js, and added custom_js.info with the following code:
name = Custom JS
description = Add your custom Javascript files here.
package = Custom Modules
core = 7.x
I then added a custom_js.module file with the following code:
<?php
function custom_js_preprocess_html(&$variables) {
drupal_add_js(drupal_get_path('module', 'custom_js') . '/js/custom.js', array(
'scope' => 'footer',
'weight' => '15'
));
}
drupal_add_css(drupal_get_path('module', 'custom_js') . '/css/custom.css');
I added folders 'js' and 'css' to my module. Notice I put the js sheet in the footer with a weight so that it loads last. In the Javascript file you should add the following code, and then you are ready to go.
(function ($) {
Drupal.behaviors.custom_js = {
attach: function (context, settings) {
// All our js code here
// end our js code
}
};})(jQuery);
About the Author:
Tommy Sliker
Web Developer
Tommy Sliker, aka Mirakolous, is a creative mastermind, Drupal Front End guru, and a contributor to Drupal Core. He has been producing his own music since he was twelve years old, and has a wide breadth of creative skills including photography, video production, and graphic design.
In addition to his Web work, Tommy's passions include music production, drums, guitar, photography,