Broadstreet blog

jQuery and Drupal 7

← All blog posts
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);

More from the blog

October 31, 2013

Bye Bye iGoogle!

After being my home page for over 6 years, iGoogle will be retiring tomorrow. I will miss it so much! I had my favorite shortcuts right there, and some…

October 2, 2013

My First Drupalcon

This week I attended my first DrupalCon, the semi-annual gathering of a diverse group of people devoted to the health & development of Drupal.

Let’s get your phone ringing

Book a free, no-pressure consultation. We’ll review your website and Google presence and show you where you can grow.

Call nowFree consult