RSS

Newsletter

The CodeKarate Newsletter is the best way for technical ninjas to keep their swords sharpened. Don't worry, we won't flood your inbox and your email address will always remain private.
Back to Top

Adding Javascript to your Drupal 7 Module

As a follow up and update to a post I wrote on Adding Javascript to your Drupal 6 module, I figured I would write a quick post on doing the same thing in Drupal 7.

It starts with adding the following line to your modules .info file (rename MYMODULE to your module name or the name you want to give to your javascript file):


scripts[] = MYMODULE.js

The next step is to create the MYMODULE.js file. The general template of the javascript file looks like:

(function ($) {
  Drupal.behaviors.MYMODULE = {
    attach: function (context, settings) {
      // Your Javascript code goes here
 
    }
  };
}(jQuery));

You can pass variables from your PHP to your Javascript file by adding the following code somewhere in your module.

drupal_add_js(array('MYMODULE' => array('tax_rate' => '0.06')), 'setting');

You can now access this variable in your JavaScript:

(function ($) {
  Drupal.behaviors.MYMODULE = {
    attach: function (context, settings) {
      // You can access the variable by using Drupal.settings.MYMODULE.tax_rate
      alert(Drupal.settings.MYMODULE.tax_rate);
 
    }
  };
}(jQuery));

Discussions

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <h2> <h3> <blockquote> <img>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <css>, <html>, <php>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <mysql>, <python>, <ruby>. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.